Saturday, April 27, 2013

SQL Saturday 215 Deck and Demos Live

Hello Dear Reader!  I'm up in Jacksonville for SQL Saturday 215. Today I'm presenting SQL Internals, Backups, and Recovery Models!  OH MY!  

I'm also going to be the MC for the SQL Iron Chef BI presentation today.  Before the festivities being I wanted to upload my deck and Demo, a few tweeks from the last presentation I did up in Boston. One of the big differences, more data for the partitioning & Peicemeal Restore demo.  I got an SSD this week, and it's time to have some fun with it!

Early morning outside the main hall SQL Saturday 215 Jacksonville

I'll be in the DBA Auditorium from 1:15 - 2:15 today.  If you'd like a copy of the deck Click Here, if you'd like a copy of the demos Click Here.

Hope to see you there!

Wednesday, April 24, 2013

The 200 Billion Dollar Tweet




Hello Dear Reader!  Ever try to convince someone that they should be paying attention to Twitter?  A co-worker, Vice President of something or other, CMO, CEO, or CIO?  

I’ve had conversations over the years with many people as to why Twitter is important to their business.  If they don’t have a dedicated “Social Media” guru or their Corporate and Legal Policies do not yet “allow” an official Twitter presence, they can still effectively market, and monitor marketing, using Hash Tags.  It’s a way of dipping your toes in the water without really diving in.

Alas most of the conversations revolve around what “real” results they can gain from Twitter.  Most lack the vision or understanding to see how it could benefit them.  Tying a dollar amount to Twitter can be difficult.  Most companies don’t track or publish earnings related around a Twitter campaign.  They do with traditional advertising, but with social media it’s hard to tie a dollar amount to it.

I was a little busy yesterday with work.  Like most days I poked my head out on Twitter and checked several new sites.  I even received some push updates to my phone via USA Today, Fox News, and the New York Times.  So Imagine my surprise when this morning while standing in line at the Starbucks in the Charlotte airport that I see this.  Twitter Terror Hoax Rocks Wall Street, AARRRUUUU?

Learning about social media occurrences the next day via the new paper.  How old fashioned.  Loosing 200 Billion dollars over 80 typed characters, not so old fashioned.

Twitter first came out I laughed at it.  Why would anyone want to have a website version of Instant Messenger, remember AOL, limited to 140 characters?  Turn around several years and I have firmly flip flopped, Oxymoron, and have drunk the Twitter Kool-Aid.

What changed my mind?  Becoming a presenter in the SQL Server Community.  I went to my first SQL Saturday and caught the bug, read TSQL Tuesday #41 Becoming a SQL Server “Presenter” GETINVOLVED!  One of the things I did was examine the really good speakers and see what they were doing.  They blogged, they were on Linked-In, they were on Twitter.  So I did all of that. 

Only after the fact did I find #SQLHelp, the hashtag that allows people to ask whatever SQL question they have and get free advice from some of the Top SQL Talent in the world.  There were situations where I had production outages and we, my fellow DBA’s and managers, used Twitter to post questions and get deep technical answers quickly.

“So Balls”, you say, “YAY you’re on Twitter.  Now what about this 200 Billion dollar Tweet?!”

At 1:07 pm, East Coast Time, the Associated Press Twitter account, currently suspended, was hacked.  The 80 characters contained within the Tweet typed by the hackers seemed particularly potent given the turmoil of the last week.  “Breaking: Two Explosions in the White House and Barak Obama is injured”.  I’m not alone in my conversion, apparently the people trading on the New York Stock Market follow the Twitter as well.


By 1:09 pm the Dow had fallen over 137 points.  While it rebounded quickly, 1:12 pm when Sam Hananel (@SamHananelAP) Tweeted, “Please ignore AP Tweet on explosions we’ve been hacked”.  The market corrected.  But did it?


My Dad does a lot of day trading.  He’s studied up on it, and I’ve learned a tiny (very tiny) little bit about it vicariously through him.  You can take options out on Stocks termed calls, where you bet they will over or under perform.

Based on their performance you get your money back and a little extra.  The most notorious case of this came during 9-11 where some nefarious people had bet on the airlines to lose money.  In regular terms though this is used daily, sometimes you win, sometimes the company you bet on wins.  It's part of our system.

*It’s a lot more complicated than that, but we’ll stick with the very basics.*  Think betting, but using the stock market.  There are also automatic options that you can set through e-investing web sites.

So it could have affected Calls.  People could have lost money.

Another way that people could have lost money on this?  Using automated software to monitor stocks.  

Quick example, I like Disney.  So I go buy some Disney stock.  Disney is a non-essential good (basically).  They make entertainment, theme parks, dresses that my daughter likes to wear, movies my kids like to watch (DAD include on this).  I don’t NEED Disney stuff.  We get it with disposable income.  We NEED food.  The mortgage HAS to be paid.  Electricity, need that too!  So when there are hard times disposable good take a hit.  Look at the stock market when 9-11 happened, the Mortgage Crisis, and other such events.

So I buy 100 Disney stock at $35 a share for $3,500.  If something happens and Disney stock drops $10 per share, I could set up a pre-arranged sell order.  At $25 sell it all.  Let’s say the stock market tanks Disney stock because a Hacker gets into their official account and announces “Disney to go bankrupt, 10,000 employees to be laid off immediately”.

My Stock dips down to $23, while I’m at work.  My e-banking software kicks in and sells all my Disney shares.  My money is down to $2500 and I’ve just lost $1000.  When it is correctly reported that Disney is not going bankrupt and is having a record Quarter beating all earnings estimates, and the stock now corrects to $40 a share, I’m no longer a stock holder.  Not only did I take a loss, but I was out on the Win too.

I just lost $1000.  I just missed out on gaining $500.  There is no customer service department.  No receipt to be returned.  I’m out.  The market was correctly reported.  Based on my input a sell order happened.  Potentially A LOT of sell orders from all sorts of people happened. 

WHAT DOES THIS MEAN

Security and Reality.  First Security.  It means some real people lost real money yesterday.  We’ll have to see what the fallout of this is.  It also means that if you do have a Corporate Twitter account you probably need to look at changing the password every 90 days, and using something like KeePass to manage your password.

Warnings aside it also means we can now put a dollar amount on Twitter.  USA Today estimated that $200 billion dollars in broader market capital was lost when the Tweet occurred.  The market rebounded and that capitol was regained, with some people suffering losses.

Before I could even finish writting this blog, there was a new story.  SEC, FBI probe fake Tweet that rocked stocks.  And another Twitter working on two-step authentication

Now Reality.  The financial world is following Twitter and most other forms of social media.  The importance of effectively using this channel to communicate with customers and the world at large is only going to gain importance as time goes on.  The most expensive Tweet in the world so far is now worth $200 Billion dollars.  How much will the next one be worth?

As always Thanks for stopping by.

Thanks,

Brad


Friday, April 12, 2013

DBA Question of The Day: What is SAVE TRANSACTION?



 Hello Dear Reader!  I was teaching a class in Chicago last week and I got a lot of really great questions.  

We only had two days so time was short.  I got an email reminder today.  So this is the first blog that will answer some questions that I didn’t get to cover in depth in class, and I thought it would be an Excellent Question of the Day!  

The Question that I got was “What is the T-SQL SAVE TRANSACTION statement used for?”

The short answer is it is a way of setting a save point in multiple Nested Explicit Transactions.  For the Long answer we’ll look a little deeper.

REFRESHER
Back in a little over two years ago I wrote a blog, We Should Have A Talk: Your Database is Using ACID.  If you are unfamiliar with ACID go read up on it, because it is fundamental to what we are doing here.

In that same blog I talk about Explicit, Implicit, and Nested Transactions.  In case you miss the ACID reading let’s cover those.

Every Transaction in SQL Server is an Implicit Transaction, unless otherwise specified.  You can turn off Implicit Transactions but that’s a talk for another time.  Implicit means implied, rather than expressly stated. 

As with the picture we don’t have to say it.  Hopefully things end a little better for us.

 SQL Server works the same way.  No, not like a cat driving a car.  Transactions are just as Implicit.

Every single ALTER TABLE, CREATE, DELETE, DENY, DROP, FETCH, GRANT, INSERT, OPEN, REVOKE, SELECT, TRUNCATE TABLE, or UPDATE is a going to be wrapped in a BEGIN TRANSACTION and end with either a COMMIT or a ROLLBACK.

Explicit means fully and clearly expressed or demonstrated; leaving nothing merely implied.



There is no mistake about it.  The following SQL Statement is an Explicit Transaction.

BEGIN TRANSACTION

     INSERT INTO dbo.myTable1 DEFAULT VALUES

COMMIT TRANSACTION

So we’ve covered Implicit and Explicit, now we get to NestedNested Transactions are multiple levels of Explicit Transactions.


For Example:



Here we have 3 levels.  However, if any one of them fail or ROLLBACK then they all Rollback.  

Some companies use Explicit Transactions as part of their error handling.  Nothing wrong with that, but wouldn’t it be nice if you could commit part of the statement, even if a later part fails?

SAVED!






Saved Transactions allow us to save our success as we go in Nested Transaction, so that a Rollback doesn’t wipe out all of our progress.  

Depending how your code works, you MIGHT be able to use this.  Test the logic very soundly.


So let’s look at how this works.  First we’ll create a Table to test out our transaction.

if exists(select name from sys.tables where name='myTable1')
begin
     drop table dbo.myTable1
end
go
create table dbo.myTable1(
          myid int identity(1,1)
          ,mychar char(50)
          ,mychar2 char(50)
          ,constraint pk_myid_mytable1 primary key clustered(myid)
          )

Now let’s create a transaction to insert some data and roll it all back.

BEGIN TRANSACTION
     INSERT INTO dbo.myTable1(mychar, mychar2)
     VALUES('some data 1', 'some more data 1')
     BEGIN TRANSACTION
          INSERT INTO dbo.myTable1(mychar, mychar2)
          VALUES('some data 2', 'some more data 2')
          BEGIN TRANSACTION
              UPDATE dbo.myTable1
              set mychar='some new data 1'
              WHERE myid=1
              BEGIN TRANSACTION
                   SELECT * FROM dbo.myTable1
              COMMIT TRANSACTION
          COMMIT TRANSACTION
     COMMIT TRANSACTION
ROLLBACK TRANSACTION

Here’s the Output from our SSMS Windows.



/*
OOPS did I say ROLLBACK!?
*/
SELECT * FROM dbo.myTable1



We had a ROLLBACK at the end.  So the work isn’t going to stick.  Sure enough another select from the table and everything is gone.  

Now let’s try the same code again, but now we’ll create a SAVE TRANSACTION and name is testSavePoint.  Note the syntax change.  *We need to call this in the ROLLBACK otherwise the whole thing will ROLLBACK again.*  ACID properties are still in play, so we need a COMMIT AFTER the ROLLBACK  
/*
Let's Try this again
*/
BEGIN TRANSACTION
     INSERT INTO dbo.myTable1(mychar, mychar2)
     VALUES('some data 1', 'some more data 1')
     SAVE TRANSACTION testSavePoint
     BEGIN TRANSACTION
          INSERT INTO dbo.myTable1(mychar, mychar2)
          VALUES('some data 2', 'some more data 2')
          save transaction testSavePoint
          BEGIN TRANSACTION
              UPDATE dbo.myTable1
              set mychar='some new data 1'
              WHERE myid=3
              BEGIN TRANSACTION
                   SELECT * FROM dbo.myTable1
              COMMIT TRANSACTION
          COMMIT TRANSACTION
     COMMIT TRANSACTION
ROLLBACK TRANSACTION testSavePoint
COMMIT TRANSACTION


Here’s our output from SSMS again.  This looks very similar to last time with only changes in the identity key.


/*
OOPS did I say ROLLBACK AGAIN!?

But did we save anything
*/
SELECT * FROM dbo.myTable1



This time however, only our Update Statement was rolled back.

“So Balls,” you say, “That’s cool, but will we actually use this?  If we are using Nested Transactions would we only want to save ½ of it?”

Excellent Question Dear Reader!  Let me answer that with a real world scenario.

I was working with some friends earlier this year.  We changed an update job that ran for hours from row-by-row logic to set based logic.  The result was minutes instead of hours.  There were two parts of this job that we worked on. 

It was a four step process.  First a range of data was selected from one table.  Second we looked for missing data and inserted anything that was missing based on matching natural keys.  Third we then looked at everything that matched and updated any rows that needed the information.  Fourth we updated the range selected in another table.  We needed all four steps to run.  A Saved Transaction wouldn’t work for us using their current logic.

However the job failed when we first ran it, because there was an error on saving the range table.  Insert and Updates worked just fine.  The job would look at the range table and try the same range.  Even though it was failing the job was reporting success because the error handling did not catch the rollback.  It was explicitly called, but executed on a GO TO on error statement.

While we would have still had to fix the error on the range table, we could have used SAVE TRANSACTION to save the insert and update.  Then moved the range table update to its own Transaction that would have better error handling.  It also would save retry operations on the job by not processing expensive Updates, Inserts, and Rollbacks.

Alright Dear Reader, there it is.  SAVE TRANSACTION and how it works with Explicit Transactions.  Thanks for the questions, keep them coming!

As always Thanks for stopping by.

Thanks,

Brad