Skip to content

Instantly share code, notes, and snippets.

@kljensen
Created December 12, 2013 21:09
Show Gist options
  • Select an option

  • Save kljensen/7935487 to your computer and use it in GitHub Desktop.

Select an option

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
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);
@kljensen

Copy link
Copy Markdown
Author

Assumes you have table created like

CREATE TABLE word_count (word varchar(200) PRIMARY KEY, count integer);

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment