Skip to content
Advertisement

Update row with select on same table

I’m trying to update row with same table query. Context:

ID        |  LANG       |  TEXT
----------------------------------
1         |  EN         |  Hello
1         |  FR         |
1         |  ES         |
2         |  EN         |  Boat
2         |  FR         |  Bateau
2         |  ES         |

I want to : For each row; if TEXT IS NULL; update it with TEXT value of row with same ID and LANG = ‘EN’.

What is the SQL request to do something like that ?

Advertisement

Answer

You don’t specify the database. The following is standard SQL:

UPDATE t
    SET TEXT = (SELECT text
                FROM t t2
                WHERE t.id = t2.id AND LANG ='EN' AND
                      TEXT IS NOT NULL
               ) 
    WHERE TEXT IS NULL;

In the event of duplicates, the following should work:

UPDATE t
    SET TEXT = (SELECT max(text)
                FROM t t2
                WHERE t.id = t2.id AND LANG ='EN' AND
                      TEXT IS NOT NULL
               ) 
    WHERE TEXT IS NULL;

EDIT:

Of course, not all databases support all ANSI standard functionality. In MySQL, you would use a join instead:

UPDATE t JOIN
       (SELECT id, max(text) as text_en
        FROM t t2
        WHERE LANG ='EN' AND TEXT IS NOT NULL
       ) ten 
       ON t.id = ten.id
    SET t.TEXT = ten.text_en
    WHERE t.TEXT IS NULL;
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement