Reputation: 461
I'm pretty new to SQL and I was wondering if I can update a column using a condition.
I have two columns, and I want to update the second one (B) only if there is something in the first one (A) :
'UPDATE Table1 SET ColumnB = (SELECT BG FROM Table2 WHERE Table1.ColumnC = BG.ColumnZ)'
How can I avoid to apply the update to the rows where column A is null ?
Upvotes: 0
Views: 95
Reputation: 1271031
One method uses EXISTS
, if you only want to update where there is a match:
UPDATE Table1
SET ColumnB = (SELECT BG FROM Table2 t2 WHERE table1.ColumnC = t2.ColumnZ)
WHERE EXISTS ( SELECT BG FROM Table2 t2 WHERE table1.ColumnC = t2.ColumnZ );
If you want to update only where the first table has a non-NULL
value, then use WHERE
in the outer query:
UPDATE Table1
SET ColumnB = (SELECT BG FROM Table2 t2 WHERE table1.ColumnC = t2.ColumnZ)
WHERE ColumnB IS NOT NULL;
Upvotes: 2