0

I have table A that contains about 10 millions rows and Table B which contains some updated information for some rows in table A and also contains new rows that don't exist in table A.

I want to update table A using table B and at the same time insert rows that have no match in tableA.

I found many answers like the solution below but it seems like they all miss the inserting part that I'm looking for.

UPDATE A 
SET code = B.code
FROM B
WHERE A.id = B.id 
1
  • If the data is in two tables, just run two queries, an update and an insert. Commented Mar 26, 2019 at 21:47

1 Answer 1

1

Use two queries:

update a
    set code = b.code
    from b
    where a.id = b.id;

insert into a (id, code)
    select id, code
    from b
    where not exists (select 1 from a where a.id = b.id);

You can also use on conflict

insert into a (id, code)
    select b.id, b.code
    on conflict on constraint a_id
    do update set code = b.code;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.