Transactions, concurrency and queries · 4 MIN READ

UPSERT with ON CONFLICT: counters, insert-if-absent and why INSERT OR REPLACE deletes rows

Write ON CONFLICT DO UPDATE and DO NOTHING statements that use excluded values and RETURNING, and explain why INSERT OR REPLACE changes rowids and fires cascading deletes.

Insert this row, or update the one that is already there is one of the most common writes in an application. Doing it as SELECT-then-INSERT in Go is a race; SQLite does it atomically with the UPSERT clause, ON CONFLICT, added in 3.24. The older INSERT OR REPLACE looks similar but is a different operation: it deletes the conflicting row and inserts a new one, which quietly changes ids and can cascade into child tables.

sqlite · A MAP OF THE IDEA

  1. Unique key as target
  2. ON CONFLICT DO UPDATE
  3. excluded.col for new value
  4. RETURNING the result

Useful when

  • One atomic statement replaces a racy read-then-write.
  • RETURNING tells you whether you inserted or updated.

Watch out

  • INSERT OR REPLACE changes rowids and cascades deletes.
  • INSERT ... SELECT needs a WHERE before ON CONFLICT.

Implementation & operation cost: A unique index on the conflict target and a clear rule for merging duplicate keys within one batch.

01

The shape of an UPSERT

ON CONFLICT (columns) names a UNIQUE or PRIMARY KEY constraint, and the clause runs only when the insert would violate that constraint. DO UPDATE SET then modifies the existing row; inside it, a bare column name is the stored value and excluded.column is the value the INSERT tried to write. A WHERE clause after DO UPDATE SET can skip the update, for example to keep the newer of two timestamps. DO NOTHING skips the row entirely. The conflict target must match an actual unique index; a column without one is an error, which is good, because it means the statement cannot silently stop deduplicating.

sql
INSERT INTO page_views (path, views, last) VALUES (?, 1, ?)
ON CONFLICT (path) DO UPDATE
  SET views = views + excluded.views,
      last  = excluded.last
  WHERE excluded.last > last
RETURNING views;
Read the code

views on the right is the stored count and excluded.views is the 1 being inserted. The optional WHERE keeps an out-of-order, older visit from overwriting last. RETURNING reports the count after the insert or the update.

02

Counters, claims, replace and merge

The program runs four cases against one file database opened with foreign keys on. A page-view counter inserts each path once and increments it afterwards, returning the new total. An email claim uses DO NOTHING with RETURNING, so a conflict produces no row. A tag is rewritten first with INSERT OR REPLACE and then with ON CONFLICT DO UPDATE, and the child table shows the difference. Last, rows are merged from a staging table with INSERT ... SELECT.

go
package main

import (
	"context"
	"database/sql"
	"errors"
	"fmt"
	"log"
	"os"
	"path/filepath"

	_ "modernc.org/sqlite"
)

func must(_ sql.Result, err error) {
	if err != nil {
		log.Fatal(err)
	}
}

func count(ctx context.Context, db *sql.DB, query string) int {
	var n int
	if err := db.QueryRowContext(ctx, query).Scan(&n); err != nil {
		log.Fatal(err)
	}
	return n
}

func main() {
	ctx := context.Background()
	dir, err := os.MkdirTemp("", "upsert")
	if err != nil {
		log.Fatal(err)
	}
	defer os.RemoveAll(dir)
	db, err := sql.Open("sqlite", "file:"+filepath.Join(dir, "app.db")+"?_pragma=foreign_keys(1)")
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	must(db.ExecContext(ctx, `CREATE TABLE page_views (
		path  TEXT PRIMARY KEY,
		views INTEGER NOT NULL,
		last  TEXT NOT NULL
	)`))

	// 1. Counter: insert the first time, add to the stored value afterwards.
	hit := `INSERT INTO page_views (path, views, last) VALUES (?, 1, ?)
		ON CONFLICT (path) DO UPDATE SET views = views + excluded.views, last = excluded.last
		RETURNING views`
	for i, path := range []string{"/", "/docs", "/", "/", "/docs"} {
		var views int
		if err := db.QueryRowContext(ctx, hit, path, fmt.Sprintf("t%d", i+1)).Scan(&views); err != nil {
			log.Fatal(err)
		}
		fmt.Printf("hit %-5s -> views=%d\n", path, views)
	}
	var last string
	if err := db.QueryRowContext(ctx, "SELECT last FROM page_views WHERE path = '/'").Scan(&last); err != nil {
		log.Fatal(err)
	}
	fmt.Println("last visit of / :", last)

	// 2. Insert-if-absent: DO NOTHING plus RETURNING yields no row on conflict.
	must(db.ExecContext(ctx, "CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT NOT NULL UNIQUE)"))
	claim := "INSERT INTO users (email) VALUES (?) ON CONFLICT (email) DO NOTHING RETURNING id"
	for _, email := range []string{"ann@example.com", "ann@example.com"} {
		var id int64
		err := db.QueryRowContext(ctx, claim, email).Scan(&id)
		switch {
		case errors.Is(err, sql.ErrNoRows):
			fmt.Println("claim", email, "-> already taken")
		case err != nil:
			log.Fatal(err)
		default:
			fmt.Println("claim", email, "-> new id", id)
		}
	}

	// 3. INSERT OR REPLACE deletes the old row first: new rowid, cascades fire.
	must(db.ExecContext(ctx, `CREATE TABLE tags (id INTEGER PRIMARY KEY, name TEXT NOT NULL UNIQUE, color TEXT)`))
	must(db.ExecContext(ctx, `CREATE TABLE post_tags (
		post   INTEGER NOT NULL,
		tag_id INTEGER NOT NULL REFERENCES tags (id) ON DELETE CASCADE
	)`))
	must(db.ExecContext(ctx, "INSERT INTO tags (name, color) VALUES ('go', 'blue')"))
	must(db.ExecContext(ctx, "INSERT INTO post_tags VALUES (1, 1), (2, 1)"))

	must(db.ExecContext(ctx, "INSERT OR REPLACE INTO tags (name, color) VALUES ('go', 'cyan')"))
	var id int64
	if err := db.QueryRowContext(ctx, "SELECT id FROM tags WHERE name = 'go'").Scan(&id); err != nil {
		log.Fatal(err)
	}
	fmt.Printf("after OR REPLACE: tag id=%d, post_tags rows=%d\n", id, count(ctx, db, "SELECT count(*) FROM post_tags"))

	must(db.ExecContext(ctx, "INSERT INTO post_tags VALUES (1, ?), (2, ?)", id, id))
	must(db.ExecContext(ctx, `INSERT INTO tags (name, color) VALUES ('go', 'teal')
		ON CONFLICT (name) DO UPDATE SET color = excluded.color`))
	if err := db.QueryRowContext(ctx, "SELECT id FROM tags WHERE name = 'go'").Scan(&id); err != nil {
		log.Fatal(err)
	}
	fmt.Printf("after DO UPDATE: tag id=%d, post_tags rows=%d\n", id, count(ctx, db, "SELECT count(*) FROM post_tags"))

	// 4. INSERT ... SELECT needs a WHERE clause before ON CONFLICT.
	must(db.ExecContext(ctx, "CREATE TABLE incoming (path TEXT, views INTEGER)"))
	must(db.ExecContext(ctx, "INSERT INTO incoming VALUES ('/', 10), ('/new', 4)"))
	_, err = db.ExecContext(ctx, `INSERT INTO page_views (path, views, last)
		SELECT path, views, 'import' FROM incoming
		ON CONFLICT (path) DO UPDATE SET views = views + excluded.views`)
	fmt.Println("without WHERE, a parse error:", err != nil)
	must(db.ExecContext(ctx, `INSERT INTO page_views (path, views, last)
		SELECT path, views, 'import' FROM incoming WHERE true
		ON CONFLICT (path) DO UPDATE SET views = views + excluded.views`))
	rows, err := db.QueryContext(ctx, "SELECT path, views FROM page_views ORDER BY path")
	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()
	for rows.Next() {
		var path string
		var views int
		if err := rows.Scan(&path, &views); err != nil {
			log.Fatal(err)
		}
		fmt.Printf("merged %-5s views=%d\n", path, views)
	}
	if err := rows.Err(); err != nil {
		log.Fatal(err)
	}
}
Read the code

The counter reaches 3 for / and 2 for /docs, and last records the fourth visit, t4. The second claim of ann@example.com hits the conflict, RETURNING yields nothing and Scan reports sql.ErrNoRows. INSERT OR REPLACE gives the go tag a new id, 2, and the cascade deletes both post_tags rows; the DO UPDATE afterwards keeps id 2 and both new links. The merge without WHERE fails to parse; with WHERE true, / grows from 3 to 13 and /new is inserted with 4.

03

DO NOTHING with RETURNING

Insert-if-absent is DO NOTHING. Adding RETURNING id tells you which case happened: one row means you created it, no row means it already existed, which database/sql reports as sql.ErrNoRows from QueryRow. If you also need the existing id, either follow up with a SELECT in the same transaction or use a no-op DO UPDATE such as SET email = excluded.email, which makes RETURNING report the existing row. Note that DO NOTHING applies only to the named conflict target; a different constraint, such as a CHECK or another UNIQUE index, still raises its error.

04

INSERT OR REPLACE is delete plus insert

OR REPLACE is a conflict resolution algorithm, not an update. When a uniqueness constraint fails, SQLite deletes the existing row and inserts the new one. Columns you did not list receive their defaults rather than keeping their old values, an INTEGER PRIMARY KEY that you did not supply gets a new rowid, and with foreign keys enabled the delete performs ON DELETE actions, which is why the link rows vanished in the program. Delete triggers fire only when recursive_triggers is on. Prefer ON CONFLICT DO UPDATE whenever existing rows have identity, children or columns you mean to keep.

05

INSERT ... SELECT needs WHERE before ON CONFLICT

When the rows come from a SELECT, the parser cannot tell whether ON starts a join constraint or the upsert clause, so INSERT ... SELECT ... FROM t ON CONFLICT fails with a syntax error near DO. The documented fix is to give the SELECT a WHERE clause, even WHERE true. Also remember that an UPSERT handles conflicts one row at a time: if two rows of the same batch share a key, the second one updates the row the first one inserted, so define what merging means for duplicates inside the batch as well as against existing rows.

TAKE THIS WITH YOU

Use ON CONFLICT (key) DO UPDATE with excluded.column for atomic insert-or-update, DO NOTHING with RETURNING to learn whether you created the row, WHERE true for INSERT ... SELECT, and avoid INSERT OR REPLACE when rows have identity or children.

Check your understanding

A tags row has child rows with ON DELETE CASCADE. You rewrite its color with INSERT OR REPLACE using the same unique name. What happens to the children?

Go to the source

Progress stays in this browser. No account needed.