Is this query safe in SQL Server?
        Posted  
        
            by xaw
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by xaw
        
        
        
        Published on 2010-04-14T22:52:58Z
        Indexed on 
            2010/04/15
            6:23 UTC
        
        
        Read the original article
        Hit count: 256
        
I have this SQL update query:
UPDATE table1 
SET table1.field1 = 1 
WHERE table1.id NOT IN (SELECT table2.table1id FROM table2);
Other portions of the application can add records to table2 which use the field table1id to reference table1.
The goal here is to remove records from table1 which aren't referenced by table2.
Does SQL Server automatically lock table2 with this kind of query so that a new record can't be added to table2 while executing this query?
I've also considered:
UPDATE table1 
SET field1 = 1 
WHERE 0 = (SELECT COUNT(*) FROM table2 WHERE table1.id = table2.table1id);
Which seems possibly safer, but much slower (because a SELECT would be called on each row of table1 instead of just one select for the NOT IN)
© Stack Overflow or respective owner