简体   繁体   中英

SQL query update performance

I'm trying to understand why an sql update with case have lower performance than two separated update with where clause.

Here are the conditions:

  • if column1 in (1, 2, 3) then set column3 = 'A'
  • else set column3 = 'B'

I have two options.

Option #1:

UPDATE tableA
SET Column3 = (CASE WHEN column1 IN (1,2,3) THEN 'A' ELSE 'B' END)

Option #2:

UPDATE tableA
SET column3 = 'A'
WHERE column1 IN (1,2,3)

UPDATE tableA
SET column3 = 'B'
WHERE column1 NOT IN (1, 2, 3)

The option #2 has the better performance than the first one.

I would appreciate if any have reason to this.

I thought the option 1 have better performance due to one query with no where clause.

You didn't show us your table and index definitions, or your query plans, so this is a guess.

Your first query basically means: update every row of the table setting the column to either 'A' or 'B' . It has no WHERE clause so it must scan the whole table and change every row.

Your second choice, with two queries, has the possibility of using an index to find the rows it must update. Between the two queries you still update all the rows. But it seems your system still save time. Possible reasons:

  1. SQL Server finds the rows faster with WHERE clauses.
  2. The number of rows updated is smaller in each query. A lot of the cost of this kind of bulk update is committing the transaction. (SQL Server bundles up all the changes and commits them to the table so they appear simultaneous to other users of the table.) It's possible the transaction of your first example was so large it involved lots of IO.

If you want to do this sort of many-row update, you would be wise to do something like this.

UPDATE tableA
SET column3 = 'A'
WHERE column1 IN (1,2,3)
AND column3 <> 'A'

This will skip the updating of rows that don't need to change.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM