Speeding UPDATEs Using the CASE Statement

Introduction

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:


BEGIN TRAN
UPDATE titles SET …
UPDATE titles SET …
COMMIT tran


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 =
CASE
    WHEN type = “business”
    THEN price * 0.75
    WHEN pub_id = “0736″
    THEN price * 0.9
END
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.

Continues…

Pages: 1 2




Related Articles :

  • No Related Articles Found

No comments yet... Be the first to leave a reply!

Software Reviews | Book Reviews | FAQs | Tips | Articles | Performance Tuning | Audit | BI | Clustering | Developer | Reporting | DBA | ASP.NET Ado | Views tips | | Developer FAQs | Replication Tips | OS Tips | Misc Tips | Index Tuning Tips | Hints Tips | High Availability Tips | Hardware Tips | ETL Tips | Components Tips | Configuration Tips | App Dev Tips | OLAP Tips | Admin Tips | Software Reviews | Error | Clustering FAQs | Performance Tuning FAQs | DBA FAQs |