UPDATE table1
SET col = 1
WHERE col2 = 'xyz'
UPDATE a
SET col = 1
FROM table1 a
WHERE col2 = 'xyz'
Which is preferred ?
One difference I could find out was that the second statement allows to use WITH NO LOCK near the 'FROM' statement. But when used near the update statement, it gives the same error message as that of the first statement
The NOLOCK and READUNCOMMITTED lock hints are not allowed for target tables of INSERT, UPDATE or DELETE statements.
Thanks So Much
They are the same.
If the UPDATE statement only involves accessing a single table, the 1st is cleaner/simpler.
If you need to do e.g. a JOIN, then assigning an alias per your 2nd example is (IMO) cleaner, like:
UPDATE a
SET a.Col = 1
FROM TableA a
JOIN TableB b ON a.Id = b.Id
WHERE b.Something = '123'
BTW, there is no point specifying a NOLOCK hint on the table being updated, so don't count that as a reason for one over the other.
You can use the FROM syntax if you need or if it's confident to use aliases (like in your example) or JOINs like this one:
UPDATE a
SET col = 1
FROM table1 a
INNER JOIN table2 b ON b.id = a.bid
WHERE b.col = 'x'
One of the common scenarios for using method 2 is if you need to update based on a filter on joined tables, e.g.
UPDATE a
SET a.col = 1
FROM table1 a inner join table2 b on a.someFK = b.somePK
WHERE a.col2 = 'xyz' and b.col3 = 'abc'
Both are good, but it depends on what you need.
The first example is simpler, but doesn't allow you to use values from other tables.
Example 2 is very useful if you have to use values from other tables to be able to update your table, like demonstrated by Mulmoth.