Skip to content

Instantly share code, notes, and snippets.

@zergin
Last active September 18, 2015 22:53
Show Gist options
  • Save zergin/3c1ea13a578ded191ed7 to your computer and use it in GitHub Desktop.
Save zergin/3c1ea13a578ded191ed7 to your computer and use it in GitHub Desktop.
PostgreSQL upserts - how to ON DUPLICATE KEY UPDATE
CREATE TABLE upserts (
"name" character varying(255) PRIMARY KEY,
"value" integer
);
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