Created
December 12, 2013 21:09
-
-
Save kljensen/7935487 to your computer and use it in GitHub Desktop.
Shows how to increment multiple word counts in Postgresql using a single round trip to the database
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 | |
| to_be_upserted (word, count) AS ( | |
| VALUES | |
| ('fudge', 1), | |
| ('baz', 1), | |
| ('foo', 2), | |
| ('bar', 2), | |
| ('bucket', 1) | |
| ), | |
| updated AS ( | |
| UPDATE | |
| word_counts | |
| SET | |
| count = word_counts.count + to_be_upserted.count | |
| FROM | |
| to_be_upserted | |
| WHERE | |
| word_counts.word = to_be_upserted.word | |
| RETURNING word_counts.word | |
| ) | |
| INSERT INTO word_counts | |
| SELECT * FROM to_be_upserted | |
| WHERE word NOT IN (SELECT word FROM updated); |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Assumes you have table created like
based on this blog post.
As you can see in the snippet, for each value, the count is incremented by the integer component if the word already exists in the database, otherwise it is inserted.