Defensive Db Programming Chapter 09

Comments: No Comments
Published on: November 22, 2010

It is down to the final two chapters of the book by Alex Kuznetsova.  Check out the previous chapter here.  The review of this book is certainly taking longer to produce than I had planned.  However, I think you find that the book is still worth it and that this little series is also worth it.  I hope that the spread of this series is at least getting to a few more people here and there and that more people may get a copy of “Defensive Database Programming”.

This chapter is about concurrent queries and Isolation Levels.  I think these seem to be a hot button of late – at least I have been hearing more and more talk about them than in the near past.  Alex starts the chapter with a stark realization.  He states:

Even the simplest SELECT, against one table, may retrieve incorrect results when the base table is being modified at the same time. (p. 297)

Think about that statement for a bit.  I imagine it won’t take you long to realize that it is true.  I am certain that you have come up with several examples that underscore that statement.

Alex then progresses through Isolation levels giving a demonstration of what will happen under the described circumstances.  This chapter is not intended to explain the differences between the Isolation levels, but merely to demonstrate what could happen – as has been the theme throughout the book to this juncture.  These examples that Alex uses first describe a theoretical problem and then he reproduces the theoretical problem with real world scenarios.

Alex also outlines in this chapter some considerations for choosing the correct Isolation level for your business needs.  Pros and Cons are weighed and usefulness of the Isolation level is discussed.  Alex also offers up the notion of using a query hint to issue a table lock when querying the database.  Due to the reciprocal effects Alex also states that it is almost never really an option.

Alex goes the extra mile in this chapter by discussing how we can minimize deadlocks.

In the end Alex makes a recommendation as to which Isolation level he would use.  Check it out and see for yourself.

Defensive Db Programming Chapter 08

Comments: 1 Comment
Published on: November 11, 2010

We are slowly getting to the end of this book by Alex Kuznetsov (Blog).  You can find more on this series by looking here.  We are now discussing chapter 8 and it is a good chapter.  This chapter delves into Error Handling.

While the use of TRY…CATCH certainly is the best way to handle errors in T-SQL, it is not without difficulties. (p. 259)

In this chapter, Alex discusses some of the problems associated with error handling and demonstrates how to resolve some of those problems.  We will also see how to use XACT_ABORT.

The first key to error handling is to prepare for unanticipated failure.  That is the crux of error handling.  We anticipate certain behaviors and code for that, anything else needs to be handled through error handling so we can see what has happened.  Code sometimes fails, and queries against the data can also fail on occasion – we need to plan for those failures.

When dealing with data modifications there are occasions when using explicit transactions is necessary due to the nature of the data modification – we would want to ensure that any and all changes to the data were rolled back.  There are other times when we would want to ensure that processing halts immediately when an error is encountered.  In such a scenario, XACT_ABORT comes in useful.  Note, however, that this setting is probably better set explicitly ON or OFF depending on the needs.

A recommendation in this chapter is to use client-side error handling for all but the simplest of error handling.  Error-handling is far more robust in other languages than it is in TSQL.  This is a recommendation that I support.  Error handling in TSQL has become better over time (i.e. with the addition of the TRY…CATCH) and is quite useful for some degrees of error handling.  One particular realm where error handling in TSQL is lacking is in the area of Code-Reuse.  The TRY…CATCH must be rewritten for each stored procedure for which you wish to enable error handling.

As always, this chapter covers some of the gotchas of error handling in TSQL and gives examples on how to implement as well as circumvent some of the problems.  Check it out!!

Blogger Awards

A few days ago I wrote about an election that was taking place (ok so it was a week ago at this point).  That election was the SQLServerpedia Awards.  My first post on that election can be found here.  I had wanted to write another post about the election and make a whole bunch of campaign promises – to help make it feel political.  One big difference is that I was going to run a positive campaign and just talk about what I would do if I were to win.

Well, I won in one of the categories and I never wrote that campaign promises post.  So, I will just tell you what I would have promised and then maybe do some of those things.

  1. I will display the trophy in my cubicle at work
  2. I will support my fellow bloggers as much as I can just as I have done in the past.  There are some exceptional bloggers out there.
  3. I will continue to work with SQL Server
  4. I will continue to blog!!!!
  5. I will also finish my series on the book review for which I won.  Then I will progress to the next book or two and write reviews for them as well.
  6. I will continue to provide posts to SQLServerPedia

Thanks to all who voted for me.  I appreciate the support.  I recommend checking out the other books in the Book Review category.  I also recommend that you read the Blogs of the other people that were nominated for the SQL Choice Awards/ SSP Awards.

In short, this award is great and I really appreciate it.  In the grand scheme of things I am happy to have received it and rest assured that it doesn’t change my blog or me – except that I will post a badge on my blog.  We also had many excellent DB professionals and bloggers who won in various other categories.

Thanks SQLServerpedia for the awards and putting on these awards for the community.

Defensive Db Programming Chapter 07

We are here again after another …um long lapse in time … and ready for another episode in this series.  Today we get to talk about chapter 7 in the book by Alex Kuznetsov (Blog).  You can find more on this series by looking here.

Advanced Use of Constraints

This chapter ties in well with chapters 4 and 6.  You may want to review those chapters as you read this chapter.  There were problems raised in those prior chapters and now they are being discussed at length in this chapter.  First order of business is to revisit the ticket tracking system that was discussed in chapter 4.

Ticket Tracking

The system was left with business rules implemented via triggers in chapter 4.  We are now going to explore using constraints in lieu of the triggers to enforce the business rules.  For sake of testing, the environment should be reset and a new environment built.  Alex provides all of the scripts to do so.  As Alex progresses through this example he lays out the assumptions and some of the problems with those assumptions.  Through a combination of Indexes and constraints.  Another item that was implemented was the use of ON UPDATE CASCADE to help ensure the business requirements could be met.  Alex talks about the implications on performance and the reasons for implementing the cascade update.  Make sure you read this chapter to find out more.

Inventory System

There is a substantial amount of discussion about a new example in this chapter.  That discussion revolves around the Inventory System and several use cases.  I recommend reading the chapter.  I am not going to discuss it beyond that here in this post.  There are a great collection of scripts to run through the example.


In this chapter Alex shows us how a combination of constraints can enforce complex business rules.  The use of constraints should be included as a viable option when trying to enforce business rules.

Once again, go get this book and read it.  It is well worth the read.

The Year of the Phantom

Tags: ,
Comments: No Comments
Published on: October 3, 2010

It is amazing how fast time moves the older (and slower) we as humans get.  Looking back on time, it doesn’t seem to have been that long since I got married.  Today marks the 15th anniversary of that occasion.  It has been a good fifteen years and both of us have learned a lot.  I would dare say that while many things have not changed, many have changed within our relationship.  That is a good thing – you can’t make a marriage work without teamwork.  We work well together.

For our anniversary celebration (we did it a day early), I took her to the Phantom of the Opera at the Venetian.  If I were to be reviewing it, I would give it high marks in most areas and I think it is a must see.  A tip though, order your tickets directly from the Venetian.  If you order from the Venetian, the initial ticket cost is cheaper than anywhere else I found the tickets.  Furthermore, I was able to find discount codes online for ticket purchases at the Venetian.  Overall cost savings was huge.

My wife and I sat front row for the show, right next to the orchestra pit.  The view was spectacular – even when we disappeared in the fog.  What we were unprepared for was the fireworks and fire plumes at various points in the show.  We like what they did with the chandelier and moving the characters from time to time throughout the audience.  Even being as close as we were, and being able to see fine details in the makeup, there were no real flaws to the production (not even in the makeup).

I would go see it again.  Just be aware that this production is not exactly the same as the production on Broadway.  This is still Andrew Lloyd Webbers work and all changes to the score were done by home.  The main changes are in scenery and transition as well as special effects.  Both versions have their highlights and are both well worth watching.

Red Pyramid

Comments: No Comments
Published on: October 2, 2010

After having read the Percy Jackson series of books, I wanted to read a few more books by Rick Riordan.  I happened across this book one day while browsing a local store.  It didn’t take much thought after seeing the cover, title and author (sometimes the cover art is important in finding a book).  The book is “The Red Pyramid (The Kane Chronicles, Book 1).

I have to remark that I was somewhat surprised by the end of the book in the vast improvement in grammatical mistakes that I noticed.  This book could have gotten away with a lot more based on the style.  At the end of the book, there were only two such mistakes that I had noticed – that is very good.  That is substantially better than the Percy Jackson series as well.  I had to bring that up since I had noted the problem in the Percy Jackson series and it is the same author.

The book takes on a different culture this time with the heroes (who are also once again godlings / demigods).  Rather than the Gods of Rome and Greece, we now get to learn a little about the Egyptian gods – mixed deeply in fantasy.  I found it intriguing – while also too similar to the Percy Jackson series.  There were substantial differences – but kind of the same feel while not being entirely the same plot.  I think it might have been recognized by the author as well when he made a subtle reference to the Percy Jackson series as our heroes arrived in Brooklyn.  I thought that was great.

This series is not about the adventures/misadventures of one teenage demi-god, but rather a brother and sister who must help each other.  There are some nice twists and turns and it should be enjoyable.

I would give this one a B+

Keys to the Demon Prison

Categories: Book Reviews, News
Comments: No Comments
Published on: September 15, 2010

I recently finished reading Fablehaven, Book 5:Keys to the Demon Prison by Brandon Mull.  I thoroughly enjoyed this book.  I found myself constantly looking forward to reading the book and couldn’t put the book down once I started reading.

This is the final installment in the Fablehaven series and it made me want to go back and reread the other four books.  There were adequate plot twists and turns – some predictable and some not.  I do wish the turns would have gone this way or that throughout the story.  I think that is natural for somebody engaged in a book like that – you want certain storylines to turn out differently or to be developed a little  bit more.

I would recommend this series to others.  This series is an adolescent type series and is great fantasy.  I found it worth the read and well edited.

Defensive Db Programming Chapter 06

Comments: No Comments
Published on: August 30, 2010

We are here again after another week and ready for another episode in this series.  Today we get to talk about chapter 6 in the book by Alex Kuznetsov (Blog).  You can find more on this series by looking here.

Common Problems with Data Integrity

Alex explains to us that SQL server has built-in tools to help maintain the integrity of the data.  He quickly lists out three areas that can be useful in maintaining Data Integrity, as well.

  1. Applications
  2. Constraints
  3. Triggers


Data integrity can be enforced from the application.  It should be noted that this could be an inefficient method of ensuring the integrity of the data.  If you try to do it from the application, be prepared for a little pain.


It is well known that using constraints is the most reliable way to enforce data integrity rules.

Using constraints in the database is helpful and quick.  If data does not meet the constraint criteria, we can prevent it from being added.  There are different kinds of constraints and one should become familiar with the various constraints.  In this section, Alex also demonstrates the differences for the three states of constraints.  It is important to understand the state of the constraint to ensure the integrity of the data is at the level your expect.

There is a section devoted to UDFs in this chapter as well.  The section is within the Constraints section and should be read.


The chapter is concluded with the discussion on using Triggers for enforcing data integrity.  Triggers are suitable in some areas where a constraint would not be suitable for enforcing data integrity.  Triggers do have their own problems that should be considered too though.  Some of the problems are with how the trigger was coded and some are inherent with the use of triggers.  It is well worth learning about these limitations by reading this section as well.  Test the samples provided and implement some of the suggestions in your triggers.


Alex concludes this chapter with the following statement:

Data integrity logic in the application layer is too easily bypassed. The only completely
robust way to ensure data integrity is to use a trusted constraint. Even then, we need to
test our constraints, and make sure that they handle nullable columns properly.

We also have a nice set of reminders of what to include in our assumptions to be tested.  The short of it, check your constraints and test as many scenarios as necessary based on your assumptions.

Defensive Db Programming Chapter 05

Comments: No Comments
Published on: August 24, 2010

We are here again after another week and ready for another episode in this series.  Today we get to talk about chapter 5 in the book by Alex Kuznetsov (Blog).  You can find more on this series by looking here.

The title of the chapter this week is “Reusing T-SQL Code.”  In this chapter, Alex covers the topics of:

  • copy and paste code
  • proper code reuse
  • View use to encapsulate simple queries
  • UDFs and parameterized queries
  • Performance issues with UDFs
  • Business logic through filtered indexes, triggers and constraints

I am going to skip the discussion on copy and paste of code and the potential problems related to that.  I think that should be highly obvious.  I think code reuse should also bring up some obvious ideas of why to do it and how it can make your code better.  Simple queries in views is also pretty straight forward.  For these first three topics, check out what Alex has to say about them in his book.

UDFs and parameterized queries

When it comes to code reuse, it is typically easier to to reuse parameterized queries through an inline UDF.  That’s not to say that it cannot or should not be done through a stored procedure.  For many scenarios and requirements, it would be easier to do a parameterized query through a function.  Alex gives examples of some of the limitations such as sorting, Insert/Exec, and nesting.  There are of course limitations that should be considered with inline UDFs.  Alex has those listed in his book.

Performance issues with UDFs

Alex makes a very good point in this section.  When trying to reuse code, we have to pay attention to performance.  Poorly written UDFs could have serious impacts on the performance of the code and that should be a great concern.  To demonstrate this, Alex has listed out an example covering the bases.  Check out his code samples and test it.

There is also another great statement in this section.

Blanket statements do not belong in database programming.

Keep that in mind.  It is very difficult to make a blanket statement and have it apply in all cases.

The final section is covering the topic of when to use Filtered Indexes, Constraints, triggers and stored procedures.  Proper use of each of these can help to enforce business logic.  It should be noted that the use of these will depend on requirements and database design.

Having a single source of the code will help to prevent unexpected bugs.  It will also help to save time on development and documentation.

Defensive Db Programming Chapter 04

Comments: No Comments
Published on: August 11, 2010

This week we will be checking out the fourth chapter of this book by Alex.  This is a continuous effort that started with my blog post on the first chapter.  In this chapter, Alex delves into a couple of features that are new with SQL 2005 that could affect your queries and alter the expected results.

The two features being described are:

  1. Snapshot Isolation
  2. Merge

In SQL 2005 we were introduced to the Snapshot Isolation features.  The default isolation prior to SQL 2005 was READ COMMITTED.  One of the primary focus points with SNAPSHOT Isolation discussed in this chapter is with regards to the usage of triggers to enforce integrity and business rules.  Again, Alex goes to the extent to show how this could be a problem, how to reproduce the problem, what the expected results should have been, and he offers up a method to overcome the potential pitfalls.

I will throw one bit of warning here though.  Read carefully through the triggers and the verbiage that Alex has used.  There is a troubleshooting trigger which Alex uses to demonstrate a point.  As a preface to the trigger he states there is an embedded query in the trigger and that it should never be rolled to production.  If one reads this quickly, they might misread that and understand it to say that a trigger should never be used in production (that is a myth out there in DBA land already as it is).  I think an inline comment in the trigger explicitly pointing out the portion that should never be used in production would be worth the effort and type space.

As we read about the Merge feature, we are reintroduced to @@ROWCOUNT and an issue that can arise in a trigger.  We have an issue arise where the MERGE can cause unwanted behavior.  I like this section of the chapter.  Alex does a good job of demonstrating this feature and has intrigued me in regards to the Merge feature.

We see some good stuff once again in this chapter on Defensive Programming.  I recommend again that you read it.

«page 2 of 3»

September 2018
« Jul    

Welcome , today is Friday, September 21, 2018