On Conflict Needs A Unique Constraint
ON CONFLICT (col) errors out when col only has a plain index; only a unique index or primary key gives the clause a constraint to arbitrate on.
Code
CREATE TABLE devices (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
serial text NOT NULL
);
-- a plain index cannot arbitrate conflicts
CREATE INDEX devices_serial_idx ON devices (serial);
-- fails with: there is no unique or exclusion constraint matching the
-- ON CONFLICT specification
INSERT INTO devices (serial) VALUES ('SN-100')
ON CONFLICT (serial) DO NOTHING;
-- swap the plain index for a unique one; the same upsert now works
DROP INDEX devices_serial_idx;
CREATE UNIQUE INDEX devices_serial_uidx ON devices (serial);
INSERT INTO devices (serial) VALUES ('SN-100') RETURNING id;
INSERT INTO devices (serial) VALUES ('SN-100')
ON CONFLICT (serial) DO UPDATE SET serial = EXCLUDED.serial
RETURNING id;What this snippet actually does — On Conflict Needs A Unique Constraint
What runs here is INSERT / UPDATE / CREATE — devices and set are the objects involved.
Concretely, the SQL combines: an upsert guard (ON CONFLICT/MERGE) that turns insert-or-update into one atomic statement; a RETURNING clause that hands the affected rows back to the caller; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; UNIQUE constraints that keep duplicate values out; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.
Using it
The devices table is the working surface here.
Key statements
INSERT INTO devices (serial) VALUES ('SN-100')
ON CONFLICT (serial) DO UPDATE SET serial = EXCLUDED.serial
RETURNING id;
CREATE TABLE devices (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
serial text NOT NULL
);
INSERT INTO devices (serial) VALUES ('SN-100')
ON CONFLICT (serial) DO NOTHING;
Interactive Tools for This Topic
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- What relations does the SQL touch?
- `devices`, `set` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.