Created
February 10, 2021 16:25
-
-
Save doctaphred/b54dc11985f6436c8707656f62b23f4d to your computer and use it in GitHub Desktop.
Bulk upsert from CSV in PostgreSQL
This file contains 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
-- See https://www.postgresql.org/docs/current/sql-copy.html | |
-- and https://www.postgresql.org/docs/current/sql-insert.html | |
CREATE TEMP TABLE temp_table | |
(LIKE table INCLUDING DEFAULTS) | |
ON COMMIT DROP; | |
COPY temp_table (col1, col2, ...) FROM STDIN WITH CSV; | |
-- Assumes no header row: add `HEADER` if it has one. | |
INSERT INTO table | |
SELECT * FROM temp_table | |
ON CONFLICT (pk) DO UPDATE | |
SET (col1=EXLCLUDED.col1, col2=EXCLUDED.col2, ...) | |
WHERE EXCLUDED.timestamp > table.timestamp; | |
-- `ON CONFLICT DO NOTHING` can also be sufficient for some use cases. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment