Upsert Against Expression Index

Target ON CONFLICT at the exact lower(email) expression; naming the bare column cannot infer the unique expression index and fails.

SqlData Integrity

Code

snippet
-- upsert against the unique expression index: conflict target must
-- repeat the exact expression, not the bare column
CREATE TABLE users (
    user_id int GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    email   text NOT NULL
);
CREATE UNIQUE INDEX users_email_lower_key ON users (lower(email));

INSERT INTO users (email) VALUES ('[email protected]')
ON CONFLICT (lower(email)) DO UPDATE SET email = EXCLUDED.email
RETURNING user_id, email;

-- bare column names cannot infer the expression index and fail with
-- "there is no unique or exclusion constraint matching the ON CONFLICT specification"
-- INSERT INTO users (email) VALUES ('[email protected]')
-- ON CONFLICT (email) DO NOTHING;

-- a case variant hits the conflict target: EXCLUDED.email writes the new casing back into the row
INSERT INTO users (email) VALUES ('[email protected]')
ON CONFLICT (lower(email)) DO UPDATE SET email = EXCLUDED.email
RETURNING user_id, email;

How the snippet works

What runs here is INSERT / UPDATE / CREATE — users and set are the objects involved.

Mechanically, the statements are built from: 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

Run the statement against the users table.

Statements that matter

INSERT INTO users (email) VALUES ('[email protected]')
ON CONFLICT (lower(email)) DO UPDATE SET email = EXCLUDED.email
RETURNING user_id, email;
INSERT INTO users (email) VALUES ('[email protected]')
ON CONFLICT (lower(email)) DO UPDATE SET email = EXCLUDED.email
RETURNING user_id, email;
CREATE TABLE users (
    user_id int GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    email   text NOT NULL
);

Interactive Tools for This Topic

FAQ

Which relations are involved here?
`users`, `set` — referenced directly, no join needed.