DEV Community

Cover image for Merge Command
Santhosh Balasa
Santhosh Balasa

Posted on • Edited on

1

Merge Command

Have you come across a situation where you have a very huge table Eg: 100 million rows and you need to update the deltas ?

Y'all probably re-create the whole table to cater such a situation, well now you do not have to fret about it, we have merge command released in Postgres 15.

Example:

create table demo (id serial primary key, val int);

inset into demo (val) select x * 10 from generate_series(1, 10) as x;

create table demo1 as (select id, id * 100 as val
 from 
generate_series(1, 10, 2) as id) ;

select * from demo order by id;
select * from demo1;

merge
into demo as d
       using demo1 as d1
on
   d.id = d1.id
   when matched then
update
set
   val = d1.val
   when not matched then
insert 
   (val)
values (d1.val) ;

select * from demo order by id;
Enter fullscreen mode Exit fullscreen mode

Viola ! Easy peasy now !

Top comments (0)

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay