On Conflict By Constraint Name

Target the conflict by constraint name with ON CONFLICT ON CONSTRAINT, pinning the arbitration to one explicit unique constraint.

SqlData Integrity

Code

sqlsnippet
17 lines
CREATE TABLE devices (
    id     bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    serial text NOT NULL,
    CONSTRAINT devices_serial_key UNIQUE (serial)
);

-- usual path: infer the arbitration target from columns
INSERT INTO devices (serial) VALUES ('SN-1')
ON CONFLICT (serial) DO UPDATE SET serial = EXCLUDED.serial
RETURNING id, serial;

-- explicit path: name the constraint instead of letting inference pick it
INSERT INTO devices (serial) VALUES ('SN-1')
ON CONFLICT ON CONSTRAINT devices_serial_key DO NOTHING
RETURNING id, serial;

SELECT id, serial FROM devices;

From setup to output — On Conflict By Constraint Name

SELECT / INSERT / UPDATE / CREATE statements share the script, touching the single relation devices; set is only the DO UPDATE SET clause, not a relation.

In terms of clauses, the statements use: 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.

Applying it

Point it at the devices table.

Statements that matter

INSERT INTO devices (serial) VALUES ('SN-1')
ON CONFLICT (serial) DO UPDATE SET serial = EXCLUDED.serial
RETURNING id, serial;
CREATE TABLE devices (
    id     bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    serial text NOT NULL,
    CONSTRAINT devices_serial_key UNIQUE (serial)
);
INSERT INTO devices (serial) VALUES ('SN-1')
ON CONFLICT ON CONSTRAINT devices_serial_key DO NOTHING
RETURNING id, serial;

Interactive Tools for This Topic

FAQ

Name the tables involved in this file.
`devices`, `set`.