Last active
September 18, 2015 22:53
-
-
Save zergin/3c1ea13a578ded191ed7 to your computer and use it in GitHub Desktop.
PostgreSQL upserts - how to ON DUPLICATE KEY UPDATE
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE TABLE upserts ( | |
"name" character varying(255) PRIMARY KEY, | |
"value" integer | |
); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
WITH | |
updated AS ( | |
UPDATE upserts | |
SET value = value + 1 | |
WHERE name = 'metric.1' | |
RETURNING * | |
), | |
new (name, value) AS ( | |
VALUES ('metric.1', 1) | |
) | |
INSERT INTO upserts | |
SELECT n.* FROM new n | |
LEFT JOIN updated u ON (u.name = n.name) | |
WHERE u.name is NULL; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment