Created
June 4, 2015 17:57
-
-
Save ykrkn/e68000ca073c62995b24 to your computer and use it in GitHub Desktop.
Postgres 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
-- обновляем все записи, которые уже есть в таблице | |
UPDATE existing_table ex | |
SET field1 = ex.field1 + up.field1, | |
field2 = up.field2, | |
… | |
FROM updates up | |
WHERE ex.pkey_field1 = up.pkey_field1 AND ex.pkey_field2 = up.pkey_field2 …; | |
-- вставляем несуществующие | |
INSERT INTO existing_table (columns, …) | |
SELECT new.field1, new.field2, … | |
FROM new_data new | |
WHERE NOT EXISTS ( | |
SELECT * FROM existing_table ex WHERE ex.pkey1 = new.pkey1 and ex.pkey2 = new.pkey2 and …; | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment