typestar

Upsert in SQL

INSERT ON CONFLICT writes a row or updates the one already there.

INSERT INTO daily_counts (day, hits)
VALUES ('2026-07-29', 1)
ON CONFLICT (day)
DO UPDATE SET
    hits = daily_counts.hits + excluded.hits;

INSERT INTO tags (name)
VALUES ('sql')
ON CONFLICT (name)
DO NOTHING;

How it works

  1. ON CONFLICT names the constraint that would be violated.
  2. excluded refers to the row you tried to insert.
  3. DO NOTHING makes the insert idempotent instead.

Keywords and builtins used here

The run, in numbers

Lines
10
Characters to type
206
Tokens
50
Three-star pace
95 tpm

At the three-star pace of 95 tokens a minute, this run takes about 32 seconds.

Type this snippet

Step 3 of 5 in Transactions, step 13 of 17 in Plans & performance.

← Previous Next →