Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Update column with values from another table if ID exists in another table

I have two tables,

Table1:

+----+-------+
| ID | Value |
+----+-------+
| 1  |   A   |
| 2  |   B   |
| 3  |   C   |
| 4  |   D   |
+----+-------+

Table2:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

+----+-------+
| ID | Value |
+----+-------+
| 3  |   E   |
| 4  |   F   |
+----+-------+

Table1 after update

+----+-------+
| ID | Value |
+----+-------+
| 1  |   A   |
| 2  |   B   |
| 3  |   E   |
| 4  |   F   |
+----+-------+

I want to update all ‘Value’ columns in table 1 where there is a matching ID in table 2, and leave the rest of the values who do not have a matching ID in table 2 to be left alone, as in the example above.

Essentially the following:

UPDATE Table1
SET Value = (SELECT Value FROM Table2 
             WHERE Table1.[ID] = Table2.[ID])

Except this makes all values in Table1 NULL that are not present in Table2. I want this to remain the same.

I’ve accomplished this before easily using an

UPDATE

with a

CASE WHEN

but I cannot remember exactly what it was.

>Solution :

Use an INNER JOIN not a subquery. This will implicitly filter to only rows where the related row is found:

UPDATE T1
SET [Value] = T2.Value
FROM dbo.Table1 T1
     JOIN dbo.Table2 T2 ON T1.ID = T2.ID;

db<>fiddle

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading