Reputation: 2564
I have a table people
with less than 100,000 records and I have taken a backup of this table using the following:
create table people_backup as select * from people
I add some new records to my people
table over time, but eventually I want to merge the records from my backup table into people
. Unfortunately I cannot simply DROP
my table as my new records will be lost!
So I want to update the records in my people
table using the records from people_backup
, based on their primary key id
and I have found 2 ways to do this:
Great! However, both of these methods use SET
and make me specify what columns I want to update. Unfortunately I am lazy and the structure of people
may change over time and while my CTAS
statement doesn't need to be updated, my update/merge script will need changes, which feels like unnecessary work for me.
Is there a way merge entire rows without having to specify columns? I see here that not specifying columns during an INSERT
will direct SQL to insert values by order, can the same methodology be applied here, is this safe?
NB: The structure of the table will not change between backups
Upvotes: 2
Views: 1029
Reputation: 231711
Given that your table is small, you could simply
DELETE FROM table t
WHERE EXISTS( SELECT 1
FROM backup b
WHERE t.key = b.key );
INSERT INTO table
SELECT *
FROM backup;
That is slow and not particularly elegant (particularly if most of the data from the backup hasn't changed) but assuming the columns in the two tables match, it does allow you to not list out the columns. Personally, I'd much prefer writing out the column names (presumably those don't change all that often) so that I could do an update.
Upvotes: 2