sqlsqlite

Update table values from another table with the same user name


I have two tables, table_a and table_b, both of which have a column called user_name.

I want to copy column_b1 and column_b2 of table_b to column_a1 and column_a2 of table_a, respectively, for the rows that share the same user_name.

How can I do it in SQL?


Solution

  • As long as you have suitable indexes in place this should work alright:

    UPDATE table_a
    SET
          column_a_1 = (SELECT table_b.column_b_1 
                                FROM table_b
                                WHERE table_b.user_name = table_a.user_name )
        , column_a_2 = (SELECT table_b.column_b_2
                                FROM table_b
                                WHERE table_b.user_name = table_a.user_name )
    WHERE
        EXISTS (
            SELECT *
            FROM table_b
            WHERE table_b.user_name = table_a.user_name
        )
    

    UPDATE in sqlite3 did not support a FROM clause for a long time, which made this a little more work than in other RDBMS. UPDATE FROM was implemented in SQLite 3.33 however (2020-08-14) as mentioned at: https://stackoverflow.com/a/63079219/895245

    If performance is not satisfactory, another option might be to build up new rows for table_a using a select and join with table_a into a temporary table. Then delete the data from table_a and repopulate from the temporary.