I have a SQL query where I am trying to update a column in a table (tblA) from data in another table (tblB). This works fine when I try to update all the records in tblA, however, in this case I only have missing data which I have identified and populated in tblB. When I try to update only the missing data the non-matched data is also updated but to NULL.
UPDATE tblA A SET A.Fld1 = ( SELECT B.Fld1 FROM tblB B WHERE A.Fld2 = B.Fld2 )
Is it possible to update only the missing data?
Yes, it is possible.
The reason some of your rows are getting NULLs updated is due to the subquery. When the subquery fails to find a matching row in tblB, the subquery returns NULL. But since the UPDATE has no WHERE clause, it will update all rows, even those where the subquery returns NULL. Consequently, to prevent this, you might do this:
UPDATE tblA A SET A.Fld1 = ( SELECT B.Fld1 FROM tblB B WHERE A.Fld2 = B.Fld2 ) WHERE EXISTS ( SELECT B.Fld1 FROM tblB B WHERE A.Fld2 = B.Fld2 )
One potential issue may arise when the subquery actually finds more than one matching row in tblB. If this happens, the UPDATE will terminate with an error ("subquery may return only one row").
Another approach is to use a joined update query. The exact SQL that is required depends on which database system you're using, but here's an example for SQL Server:
update tblA set Fld1 = B.Fld1 from tblA A inner join tblB B on A.Fld2 = B.Fld2
Note that only rows that have a match are updated.
This was first published in May 2007