Merge a Batch Into a Daily Counter
daily holds one row per day with a running
views total. A batch of new counts has arrived in
batch. Merge it in:
- a day already in
dailyhas the batch count added to its total - a day not yet in
dailyis inserted batchcontains more than one row for the same day, and all of them count
Then return the final table:
SELECT day, views FROM daily ORDER BY day;
Do the merge with one statement — no
SELECT to find out which days exist first. Two copies of this
running at the same time must not lose a count or fail.
Expected output
day | views
-----------+------
2024-03-01 | 115
2024-03-02 | 220
2024-03-03 | 30
2024-03-04 | 40
Editorial
INSERT INTO daily (day, views)
SELECT day, sum(views) FROM batch GROUP BY day
ON CONFLICT (day) DO UPDATE
SET views = daily.views + excluded.views;
The GROUP BY is not optional
Run the starter and PostgreSQL refuses it:
ON CONFLICT DO UPDATE command cannot affect row a second time
That error is the engine telling you something precise.
ON CONFLICT resolves each conflicting row against the table
as it was when the statement started, so two batch rows for 2024-03-01
both conflict with the same existing row and the second has nothing coherent to
do — the first update is not visible to it, so adding to it would lose the 10.
Rather than silently drop one, PostgreSQL errors. Collapsing the batch to one
row per day with GROUP BY removes the ambiguity before the
statement sees it.
This is the most common way a working upsert breaks in production: it is written against a batch that happens to be unique, and the day a duplicate arrives the whole job fails.
excluded
excluded is the row that would have been inserted. So
daily.views + excluded.views is "what is stored, plus what
arrived". The two prefixes matter:
SET views = excluded.views would replace the total instead of
adding to it, which is the right answer for a last-write-wins cache and the
wrong one for a counter.
The race this avoids
The version people write first:
-- WRONG under concurrency
SELECT views FROM daily WHERE day = '2024-03-01';
-- application decides: row exists, so update
UPDATE daily SET views = views + 15 WHERE day = '2024-03-01';
and for a day that does not exist yet, the SELECT returns
nothing and the application inserts. Two workers running that at the same
moment both see nothing and both insert, and one gets a duplicate-key error — or
worse, with no primary key, both succeed and the day now has two rows.
Raising the isolation level does not fix it. 💡 READ COMMITTED, the
PostgreSQL default, means each statement sees data committed before that
statement began — so the gap between your SELECT and your UPDATE is exactly
where another transaction's commit fits. REPEATABLE READ makes it worse in
a sense: the second worker's update finds the row changed underneath it and
aborts with a serialization failure, which you then have to retry. The reason
ON CONFLICT works is that it is one statement:
the conflict detection and the write happen under the same row lock, with no
window in between for anything to change.
DO NOTHING, and the conditional form
INSERT INTO daily (day, views) VALUES ('2024-03-01', 10)
ON CONFLICT (day) DO NOTHING;
"Insert if absent, ignore if present" — the idempotent-insert idiom, and the
right tool when the arriving row is a fact rather than an increment. The
DO UPDATE form also takes a filter:
ON CONFLICT (day) DO UPDATE SET views = excluded.views
WHERE daily.views < excluded.views;
which only overwrites when the new value is larger. Useful for
high-water-mark columns, and worth knowing that a row skipped by that
WHERE is simply not updated — no error, and
RETURNING gives you nothing for it, which is how you find out.
The conflict target has to be a real constraint
ON CONFLICT (day) works because day is the primary
key. Name a column with no unique index and PostgreSQL rejects the statement —
there is no constraint for it to detect a conflict on. That makes
ON CONFLICT a consumer of your schema design rather than a
substitute for it: the upsert is only possible because somebody declared what
uniqueness means first.
What an interviewer is checking
Whether you reach for one statement or for check-then-write. Describing the
race in the second — two workers, both see nothing, both insert — is the answer;
the ON CONFLICT syntax is the easy half. Mentioning the duplicate
batch rows before they bite you is what separates a good answer from a correct
one.
batch
5 rows
| idinteger | daydate | viewsinteger |
|---|---|---|
| 1 | 1709251200000000 | 10 |
| 2 | 1709337600000000 | 20 |
| 3 | 1709424000000000 | 30 |
| 4 | 1709251200000000 | 5 |
| 5 | 1709510400000000 | 40 |
daily
2 rows
| daydate | viewsinteger |
|---|---|
| 1709251200000000 | 100 |
| 1709337600000000 | 200 |