brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: INSERT … ON CONFLICT DO UPDATE is the SQLite upsert in one statement

Sqlite
~/tips/tip-sqlite-upsert-on-conflict

INSERT INTO counter VALUES ('home', 1)

Inserts a row or updates the existing one in a single statement, without a SELECT first.

The pattern “look up the row, insert if missing, update if there” needs two queries and can race. SQLite has had a proper upsert since 3.24.

CREATE TABLE counter (name TEXT PRIMARY KEY, hits INT);
INSERT INTO counter VALUES ('home', 1)
  ON CONFLICT(name) DO UPDATE SET hits = hits + 1;

The first run inserts home with 1. Every run after that hits the primary key, and the DO UPDATE part runs instead, so the counter goes up. Two runs leave hits at 2.

Inside the update, excluded refers to the row you tried to insert. That’s how you overwrite with new values:

INSERT INTO settings(key, value) VALUES ('theme', 'dark')
  ON CONFLICT(key) DO UPDATE SET value = excluded.value;

ON CONFLICT DO NOTHING just skips duplicates.

The column list after ON CONFLICT must match a unique index or the primary key exactly, or you get an error. And it is different from INSERT OR REPLACE, which I avoid for this. REPLACE deletes the old row and inserts a new one, so columns you didn’t give fall back to their defaults. With foreign keys on, that delete also sets off ON DELETE CASCADE, which removes the child rows. The upsert changes the existing row in place.

Further reading: SQLite UPSERT

More Sqlite tips SELECT unixepoch('2026-01-01 00:00:00'); SELECT name, iif(qty > 0, 'in stock', 'sold out') AS state sqlite3 -bail app.db < migrate.sql CREATE INDEX 'orders_user_id' ON 'orders'('user_id'); –> users(id) CREATE INDEX users_active_email ON users(email) WHERE active = 1; All Sqlite tips (27) All topics

Link