← Back to SQL, page 17

sql-0332 · Medium mid

A page-view counter keeps losing the first_seen date. Find the cause.

INSERT OR REPLACE deletes the conflicting row and inserts a new one, so columns not listed in the insert reset to their defaults (NULL here) and the count restarts. Use INSERT ... ON CONFLICT (page) DO UPDATE SET views = views + 1, which updates the existing row in place.

Full answer
sql
CREATE TABLE pv_bad (page TEXT PRIMARY KEY, views INTEGER NOT NULL, first_seen TEXT);
CREATE TABLE pv_good (page TEXT PRIMARY KEY, views INTEGER NOT NULL, first_seen TEXT);
INSERT INTO pv_bad VALUES ('home', 5, '2026-01-01');
INSERT INTO pv_good VALUES ('home', 5, '2026-01-01');

The query as written:

sql
INSERT OR REPLACE INTO pv_bad (page, views) VALUES ('home', 1);
SELECT * FROM pv_bad;
pageviewsfirst_seen
home1NULL

REPLACE resolves the primary key conflict by removing the old row. The new row has views = 1 and first_seen = NULL, so both history and the running count are gone. It also fires delete triggers and, with foreign keys on, can cascade deletes.

A corrected version:

sql
INSERT INTO pv_good (page, views, first_seen) VALUES ('home', 1, '2026-03-09')
ON CONFLICT (page) DO UPDATE SET views = pv_good.views + 1;
SELECT * FROM pv_good;
pageviewsfirst_seen
home62026-01-01

The upsert keeps the row, increments views to 6 and leaves first_seen alone, because the SET list names only views. The same ON CONFLICT syntax works in PostgreSQL, where excluded.col refers to the value that was proposed for insertion.

sql
CREATE TABLE pv_bad (page TEXT PRIMARY KEY, views INTEGER NOT NULL, first_seen TEXT);
CREATE TABLE pv_good (page TEXT PRIMARY KEY, views INTEGER NOT NULL, first_seen TEXT);
INSERT INTO pv_bad VALUES ('home', 5, '2026-01-01');
INSERT INTO pv_good VALUES ('home', 5, '2026-01-01');

INSERT OR REPLACE INTO pv_bad (page, views) VALUES ('home', 1);
SELECT * FROM pv_bad;

INSERT INTO pv_good (page, views, first_seen) VALUES ('home', 1, '2026-03-09')
ON CONFLICT (page) DO UPDATE SET views = pv_good.views + 1;
SELECT * FROM pv_good;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • REPLACE is delete plus insert
  • Unlisted columns reset under REPLACE
  • ON CONFLICT DO UPDATE changes the row in place
  • excluded refers to the proposed row

Common mistakes

  • Using REPLACE as a generic upsert
  • Forgetting that REPLACE can cascade deletes

Follow-ups

  • How would you insert many rows and add their counts?
  • How does MySQL's ON DUPLICATE KEY UPDATE compare?

Tips

  • Name delete-then-insert as the cause