1

I have a problem with filling empty cells in one table with data from another one.

I got a table with user emails - some of the fields are empty, some are already containing emails. I gathered the list of emails from the users who doesn't have emails in the table. I am going to import it as an separate table, and then update an exiting one. So to demonstrate:

Existing table (USERS):

ID      Email
1       aaa@bbb.com
2       NULL
3       bbb@bbb.com
4       NULL
5       NULL

The second table (MYTABLE) has exactly the same structure, but it has only ID and Emails of users who have NULL in original one.

I used this as a test, but find out that that code is overwriting emails if this user exist in both tables, and I don't want this:

UPDATE users
SET users.email = (SELECT mytable.email
                     FROM mytable
                     WHERE mytable.id = users.id)
WHERE EXISTS (SELECT mytable.email
                     FROM mytable
                     WHERE mytable.id = users.id);

So is it possible to update ONLY cells with NULL value?

peterh
  • 2,077
  • 8
  • 28
  • 40
AKarpun
  • 113
  • 3

1 Answers1

1

This would work ;

UPDATE users
SET users.email = (SELECT mytable.email
                     FROM mytable
                     WHERE mytable.id = users.id)
WHERE EXISTS (SELECT mytable.email
                     FROM mytable
                     WHERE mytable.id = users.id)
AND users.email IS NULL;
druzin
  • 2,308
  • 13
  • 15