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.
Code
-- 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
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.Cron Expression ExplainerParse a five-field cron expression and get a field-by-field plain-English explanation plus a one-line human-readable schedule summary.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.
FAQ
- Which relations are involved here?
- `users`, `set` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.