Created
June 19, 2013 13:54
-
-
Save anonymous/5814504 to your computer and use it in GitHub Desktop.
Batch 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 | |
-- write the new values | |
n(ip,visits,clicks) AS ( | |
VALUES ('192.168.1.1',2,12), | |
('192.168.1.2',6,18), | |
('192.168.1.3',3,4) | |
), | |
-- update existing rows | |
upsert AS ( | |
UPDATE page_views o | |
SET visits=n.visits, clicks=n.clicks | |
FROM n WHERE o.ip = n.ip | |
RETURNING o.ip | |
) | |
-- insert missing rows | |
INSERT INTO page_views (ip,visits,clicks) | |
SELECT n.ip, n.visits, n.clicks FROM n | |
WHERE n.ip NOT IN ( | |
SELECT ip FROM upsert | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment