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.

SqlData Integrity

Code

snippet
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

FAQ

What relations does the SQL touch?
`devices`, `set` — referenced directly, no join needed.