Skip to content

Instantly share code, notes, and snippets.

@jimytc
Created March 24, 2016 16:27
Show Gist options
  • Save jimytc/13bf59aae837e12ab8ba to your computer and use it in GitHub Desktop.
Save jimytc/13bf59aae837e12ab8ba to your computer and use it in GitHub Desktop.
Use WITH queries to do UPSERT
WITH creations_need_move AS (
SELECT id, type
FROM creations
WHERE type IS NOT NULL
),
update_existing_metadata AS (
UPDATE creation_metadata (creation_id, category)
SET category = source.type
FROM creations_need_move source
WHERE creation_id = source.id
RETURNING creation_metadata.*
)
INSERT INTO creation_metadata (creation_id, category)
SELECT id, type
FROM creations_need_move
WHERE NOT EXISTING ( SELECT 1
FROM update_existing_metadata up
WHERE up.creation_id = creations_need_move.id )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment