Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MERGE syntax used to UPSERT or INSERT on duplicate UPDATE

So I'm coming from MySQL where I could do INSERT on DUPLICATE UPDATE:

INSERT INTO table (a,b,c) 
VALUES (1,2,3)
ON DUPLICATE KEY UPDATE c=c+1;

But now I'm using PostgreSQL and there are efforts to add the UPSERT functionality, looks like MERGE might work for what I would like but wanted to see if this is the most optimal syntax. Example Syntax 1, I've also seen this but don't understand how to implement. I haven't tried this yet because I thought MERGE was used for merging data from table1 to Table2 or would something like this work?

MERGE
INTO    table
USING   table
ON      c = 1
WHEN MATCHED THEN
UPDATE
SET     c=c+1
WHEN NOT MATCHED THEN
INSERT  (a,b,c)
VALUES  (1,2,3)

Any other suggestions?

like image 891
Phill Pafford Avatar asked Dec 29 '10 16:12

Phill Pafford


1 Answers

Until MERGE is available, use this robust approach: Insert, on duplicate update in PostgreSQL?

like image 71
Michael Buen Avatar answered Sep 23 '22 19:09

Michael Buen