Question

I need to update a table from another one, and I need to update all columns, My questions is that, besides list every column in the SET, is there a way to update them all like this:

update tableA
set * = tableB.*
from tableB where tableA.id = tableB.id

I tried in psql, it doesn't work.. I have to list every column like this:

update tableA
set c1 = tableB.c1, c2 = tableB.c2, ...
from tableB where tableA.id = tableB.id

tableB is created use create..like tableA. So they are basically identical. And the reason I'm doing it is that I need load .csv data to temp table tableB and then update tableA based on the new data in tableB. tableA needs to be locked as little as possible and tableA needs to keep integrity. I'm not sure 'delete then insert' would be a good option?

Thanks!

Was it helpful?

Solution

You could delete and re-insert, if the two tables have the same columns in the same order. Assuming that all records in tableB match tableA:

delete from tableA
    where id in (select id from tableB)

insert into tableA
    select *
    from tableB;

(If all records do not match, you could use a temporary table to keep the necessary ids.)

Generally, I oppose doing insert without a column list. In some cases, it is tolerable -- such as when tableB was created as a subset from tableB using *.

OTHER TIPS

Depends on your use case and will cause locks but of a different type. Approach that works well for some scenarios.

BEGIN;
    DROP TABLE IF EXISTS tableA_old;
    ALTER tableA RENAME TO tableA_old;
    ALTER tableB RENAME TO tableA;
COMMIT;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top