Ask the Expert

UPDATE only rows which match another table in SQL

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?

    Requires Free Membership to View

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 )

More on Oracle and SQL

Read this expert response about dynamic query failing

Check out this question about an inconsistent data type error

Learn to manage SQL parent table-child table relationships

 

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

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to: