Created
March 24, 2016 16:27
-
-
Save jimytc/13bf59aae837e12ab8ba to your computer and use it in GitHub Desktop.
Use WITH queries to do UPSERT
This file contains hidden or 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 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