Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Write an idempotent upsert for page_views(page_id, day, views) that adds 1 to views or inserts a new row with 1, in PostgreSQL and MySQL 8.4. What must exist for it to work?

A UNIQUE constraint or primary key on (page_id, day) must exist, because it is what the database checks to detect the existing row. In PostgreSQL we write INSERT INTO page_views(page_id, day, views) VALUES ($1, $2, 1) ON CONFLICT (page_id, day) DO UPDATE SET views = page_views.views + 1, and in MySQL 8.4 INSERT INTO page_views(page_id, day, views) VALUES (?, ?, 1) AS new ON DUPLICATE KEY UPDATE views = page_views.views + 1. Each statement is atomic with respect to concurrent upserts, unlike a SELECT followed by an INSERT in application code.

Background to this question

Counting things per day, such as page views, API calls or logins, is one of the most common write patterns there is, and it is often the first place a team meets a race condition. The obvious code checks whether today's row exists and then inserts or updates it, and under load it either loses counts or fails with duplicate key errors. A single upsert statement solves this properly. In this answer, we will see why the check-then-insert code is broken, what the unique constraint does, write the upsert in PostgreSQL and MySQL, look at EXCLUDED and the row alias, and then answer the question hidden in the word idempotent.

1Why Check-Then-Insert Is Broken

The first version many of us write looks like this: select the row for this page and day, and if there is none, insert one with views = 1, otherwise update it. It looks correct when we read it line by line, but two requests for the same page at the same moment can interleave.

Java
// Not safe under concurrency
Optional<PageView> row = repo.findByPageIdAndDay(pageId, day);
if (row.isEmpty()) {
repo.save(new PageView(pageId, day, 1)); // request B may be doing the same right now
} else {
row.get().setViews(row.get().getViews() + 1);
}
Step throughTwo requests counting the first view of the day
Request ADatabaseRequest B
SELECT row for (7, today)
no row
SELECT row for (7, today)
no row
INSERT (7, today, 1)
INSERT (7, today, 1)
duplicate key error, or a second row if no constraint

7 messages in order. Play them, or step through them one at a time.

Both requests see no row and both insert. With a unique constraint, request B fails with a duplicate key error; without one, the table gets two rows for the same page and day, and reports double count. The update branch has a similar race: two requests read 41 and both write 42, losing one view. The problem is that the decision is made in the application, on information that is already stale when it acts.

2What the Unique Constraint Is For

An upsert lets the database make that decision atomically, but it needs a way to know what counts as the same row. That is the unique constraint, or the primary key, on (page_id, day). When an insert would create a second row with the same pair, the unique index detects it, and the upsert switches to its update action. Without the constraint, there is no conflict to detect: PostgreSQL rejects ON CONFLICT (page_id, day) with an error saying there is no unique or exclusion constraint matching the specification, and MySQL would simply insert a duplicate row.

SQL
CREATE TABLE page_views (
page_id bigint NOT NULL,
day date NOT NULL,
views bigint NOT NULL,
PRIMARY KEY (page_id, day) -- the conflict target
);

3The PostgreSQL Upsert

In PostgreSQL the conflict target names the columns of that unique constraint, and DO UPDATE says what to do when the row already exists.

SQL
INSERT INTO page_views (page_id, day, views)
VALUES (7, DATE '2026-11-05', 1)
ON CONFLICT (page_id, day)
DO UPDATE SET views = page_views.views + 1
RETURNING views;
-- 1 first call: the row is inserted
-- 2 second call: the existing row is incremented
-- 3 third call

Inside DO UPDATE, page_views.views refers to the existing row in the table. PostgreSQL also gives us a special name, EXCLUDED, for the row we tried to insert. Here the proposed views is always 1, so SET views = page_views.views + EXCLUDED.views means the same thing and reads well when we add more than one at a time, for example when a batch has already counted 25 views in memory.

The statement is atomic with respect to other upserts on the same key. If two sessions run it at the same moment for page 7 and today, one inserts, the other waits for it on the unique index and then performs the update, so the result is 2, never a duplicate error and never a lost count.

4The MySQL 8.4 Upsert

MySQL uses INSERT ... ON DUPLICATE KEY UPDATE. It reacts to a conflict on any unique index or the primary key of the table, so there is no conflict target to name. Since MySQL 8.0.19, we can give the proposed row an alias with AS, which plays the role of EXCLUDED.

SQL
INSERT INTO page_views (page_id, day, views)
VALUES (?, ?, 1) AS new
ON DUPLICATE KEY UPDATE views = page_views.views + new.views;
-- 1 row affected: inserted
-- 2 rows affected: an existing row was updated
-- Older spelling, deprecated since 8.0.20
ON DUPLICATE KEY UPDATE views = views + VALUES(views);

The VALUES() function inside ON DUPLICATE KEY UPDATE still works but is deprecated and may be removed, so new code should use the row alias. Notice also MySQL's affected-rows convention: 1 for an insert, 2 for an update, and 0 if the update did not change the row, which lets the caller tell which branch ran. Because MySQL considers every unique index, a table with a second unique key can make the update hit an unexpected row, so for upserts it is good to have only the one unique key we intend.

5Calling It From Spring

Spring Data's save() cannot express this, because it decides between insert and update in Java, which is exactly the race we wanted to avoid. A native query with @Modifying sends the upsert as one statement.

Java
public interface PageViewRepository extends JpaRepository<PageView, PageViewId> {
@Modifying
@Query(value = """
INSERT INTO page_views (page_id, day, views) VALUES (:pageId, :day, 1)
ON CONFLICT (page_id, day) DO UPDATE SET views = page_views.views + 1
""", nativeQuery = true)
int increment(long pageId, LocalDate day); // call inside a @Transactional method
}

For very hot pages, thousands of increments per second on one row create lock contention, since every upsert has to wait its turn on that row. A common remedy is to count in memory for a second or two and upsert the batch total with EXCLUDED.views, or to spread a counter over several rows and sum them when reading.

6Follow-up questions

Is incrementing a counter idempotent if the client retries?

No. The upsert is atomic, which means concurrent calls do not collide, but it is not idempotent, which would mean calling it twice has the same effect as calling it once. If a client sends a view, the server increments, and the response is lost, a retry increments again and the count is one too high. To make it idempotent, each event needs a unique id. We insert that id into a processed_events table with ON CONFLICT DO NOTHING and only increment when the insert actually added a row, both in one transaction, or in one statement with a CTE whose increment depends on the insert's RETURNING. For page views a tiny overcount is often acceptable; for money or quotas it is not.

Why not catch the duplicate key exception and retry as an update?

It works, but in PostgreSQL a failed statement aborts the whole transaction, so we would need a savepoint for each attempt, and the exception path is slow and noisy in logs. The upsert handles the conflict inside the database in one round trip, which is simpler and faster.

7Conclusion

In this answer, we saw why selecting and then inserting in application code loses counts or causes duplicate key errors, and why the upsert needs a unique constraint on (page_id, day) as its conflict target. We wrote it with ON CONFLICT ... DO UPDATE in PostgreSQL, where EXCLUDED names the proposed row, and with ON DUPLICATE KEY UPDATE and a row alias in MySQL 8.4, where VALUES() is deprecated, and noted that atomic is not the same as idempotent when clients retry.

What to say in the interviewAbout 80 seconds aloud

Open with

First, there must be a unique constraint or primary key on page_id and day, because that's what the database uses to detect that the row already exists; without it there's no conflict, and PostgreSQL even rejects the ON CONFLICT clause.

Then, if they want more

In PostgreSQL I'd write INSERT INTO page_views page_id, day, views VALUES the page, the day, 1, ON CONFLICT on page_id and day DO UPDATE SET views = page_views.views + 1. EXCLUDED refers to the row I tried to insert, so views + EXCLUDED.views also works and is handy when I upsert a batched count. In MySQL 8.4 it's INSERT ...

VALUES ?, ?, 1 AS new ON DUPLICATE KEY UPDATE views = page_views.views + new.views; the old VALUES function form is deprecated. The point of doing it in one statement is atomicity: concurrent upserts for the same key serialize on the unique index, so one inserts and the other updates, with no duplicate key error and no lost increment.

A SELECT and then INSERT or UPDATE in application code races, and Spring Data's save does exactly that, so I'd use a native modifying query. But it's not idempotent on retries: a retried request counts twice, so if that matters, I'd dedupe on an event id.

About this answer

Last updated
12 November 2026
Versions it names
MySQL 8.4, MySQL 8.0
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Write an idempotent upsert for page_views(page_id, day, views) that adds 1 to views or...": https://scrivio-interview-library.netlify.app/databases/sql-fundamentals/6e88f84017/