Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL UPDATE TOP () or UPDATE with SELECT TOP

I have couple thousands records and I need to update them in batches of 350 records.

I would like to know if there is any difference in the below two update statements and if one of them would work faster, use less database resources etc.

Statement 1:

UPDATE TOP (350) database1
SET value1 = '', value2 ='', value3 = ''
WHERE value1 = '123'

Statement 2:

    UPDATE database1
    SET value1 = '', value2 ='', value3 = ''
    WHERE ID in 
       (SELECT TOP 350 ID FROM database1
       WHERE value1 = '123')
like image 492
Rudixx Avatar asked Feb 01 '17 10:02

Rudixx


Video Answer


1 Answers

First statement will be faster. But the top 150 records are chosen randomly. Records updated in both the queries might not be same. Since you are spitting the updates into batches your approach may not update all records.

I will do this using following consistent approach than your approach.

;WITH cte
     AS (SELECT TOP (350) value1,
                          value2,
                          value3
         FROM   database1
         WHERE  value1 = '123'
         ORDER  BY ID -- or any other column to order the result 
        )
UPDATE cte
SET    value1 = '',
       value2 = '',
       value3 = '' 

Also you don't have to worry transaction log size when updating couple thousands records there is no need of batches here

like image 104
Pரதீப் Avatar answered Sep 26 '22 14:09

Pரதீப்