Skip to content

Instantly share code, notes, and snippets.

@kmatt
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kmatt/9053744 to your computer and use it in GitHub Desktop.
Save kmatt/9053744 to your computer and use it in GitHub Desktop.
PostgreSQL upsert pattern from writable CTE
WITH upsert AS (
UPDATE target
SET col1 = s.col1,
col2 = s.col2,
...
FROM source s
WHERE s.key = target.key
RETURNING s.*
)
INSERT INTO target ( ... )
SELECT key,
col1,
col2,
...
FROM source s
WHERE NOT EXISTS (SELECT * FROM upsert u WHERE u.key = s.key);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment