Speeding UPDATEs Using the CASE Statement

One of the keys to SQL Server database performance if keeping your transactions as short as possible. In this article we will look at a couple of tricks using the CASE statement to perform multiple updates on a table in a single operation. By doing this, some transactions can be shorted, and performance boosted.

Multiple Updates to a Single column

This example uses the pubs database to adjust book prices for a sale by different amounts according to different criteria. In this example, I am going to knock 25% off the price of all business books from any publisher, and 10% off any non-business books from one particular publisher. To accomplish this, you might be tempted to wrap two separate UPDATE statements into one transaction like this:
UPDATE titles SET …
UPDATE titles SET …
The down side of this technique is that it will read through the table twice, once for each update. If we code our update like the example below, then the table will only need to be read once. For large tables, this can save us a lot of disk I/O, especially if the query requires a table scan over a long table
UPDATE titles
SET price =
    WHEN type = “business”
    THEN price * 0.75
    WHEN pub_id = “0736”
    THEN price * 0.9
WHERE pub_id = “0736” OR type = “business”
Note that there is a definite “top-down” priority involved in the CASE statement. For business books from publisher 0736, the “business” discount will apply because this is the first condition in the list to be fulfilled. However, we will not give a further 10% publisher discount, even though the criteria for the second “when” clause is satisfied, because the CASE statement only evaluates criteria until it finds the first one that fits.


Leave a comment

Your email address will not be published.