Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL UPDATE statement to update a column based on another existing row

Tags:

sql

mysql

Basically I have a table that has similar format to the below table.

What I want to do is update Col4 based on this logic

  • if Col2 is null then update Col4 with Col3
  • if Col2 is not null then find the the value in Col1 which matches the value in Col2. update col4 with with the corresponding value in col3

For example given this table:

| Col1 | Col2 | Col3 | Col4 |
-----------------------------
|  1   |   2  |  A1  |  2   |
-----------------------------
|  2   |   3  |  A2  |  3   |
-----------------------------
|  3   |{null}|  A3  |{null}|

Update it to be this table

| Col1 | Col2 | Col3 | Col4 |
-----------------------------
|  1   |   2  |  A1  |  A2  |
-----------------------------
|  2   |   3  |  A2  |  A3  |
-----------------------------
|  3   |{null}|  A3  |  A3  |

Any direction would be greatly appreciated!

like image 414
mattchong Avatar asked Aug 01 '26 17:08

mattchong


1 Answers

Something like this should work (untested):

UPDATE  table
SET     col4 = CASE WHEN table.col2 IS NULL THEN table.col3 ELSE col2Matches.col3 END
FROM    table
        INNER JOIN table AS col2Matches
            ON  table.col2 = col2Matches.col1

this should let you test it:

SELECT  CASE WHEN table.col2 IS NULL THEN table.col3 ELSE col2Matches.col3 END
FROM    table
        INNER JOIN table AS col2Matches
            ON  table.col2 = col2Matches.col1

Hope this helps,

Pete

like image 100
pete Avatar answered Aug 04 '26 11:08

pete