0

I have two tables Table_A and Table_B. How can I write a conditional SQL that does the following logic

If table A records match table B records on id
then
    delete records from table A and Insert records into Table B

How can I do this with SQL most likely using with

delete from Table_A where Exists (select a.id from TABLE_A
join TABLE_B as b on a.id = b.id)

The Insert is:Insert into Table_A (id) select id from TABLE_B

1 Answer 1

3

Use a CTE to catch the ids of the deleted records, and re-join these with the b records:

WITH del AS (
        DELETE FROM a
        WHERE EXISTS ( SELECT *
                FROM b
                WHERE b.id = a.id
                )
        returning *
        )
INSERT INTO a (id, x, y, z)
SELECT id, x, y, z
FROM b
WHERE EXISTS (
        SELECT *
        FROM del
        WHERE del.id = b.id
        );

BTW: you should have very good reasons (such as wanting to activate the triggers) to prefer delete+insert to a update.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes. I am trying to avoid update because of the geometry complexities

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.