On Conflict Infers Partial Index Predicate
Upsert against a partial unique index: ON CONFLICT (email) WHERE deleted_at IS NULL selects the arbiter, and the bare column list fails outright.
Code
CREATE TABLE members (
email text NOT NULL,
deleted_at timestamptz
);
-- 部分唯一索引:只约束未删除行
CREATE UNIQUE INDEX members_active_email
ON members (email) WHERE deleted_at IS NULL;
INSERT INTO members VALUES ('[email protected]', NULL);
-- 推断必须带 index_predicate,否则找不到匹配约束而报错:
-- INSERT INTO members VALUES ('[email protected]', NULL) ON CONFLICT (email) DO NOTHING;
INSERT INTO members VALUES ('[email protected]', NULL)
ON CONFLICT (email) WHERE deleted_at IS NULL DO NOTHING;
-- 谓词外的行不进 arbiter:软删除副本直接插入,不触发冲突
INSERT INTO members VALUES ('[email protected]', now());
SELECT email, deleted_at FROM members ORDER BY deleted_at NULLS FIRST;How the snippet works
The file runs SELECT / INSERT / CREATE statements, touching members.
What the statements actually assemble: a WHERE clause that keeps only the rows a statement is meant to touch; an ORDER BY that fixes the output order; an upsert guard (ON CONFLICT/MERGE) that turns insert-or-update into one atomic statement; NOT NULL qualifiers on the required columns; UNIQUE constraints that keep duplicate values out.
Applying it
The members table is the working surface here.
Statements that matter
INSERT INTO members VALUES ('[email protected]', NULL)
ON CONFLICT (email) WHERE deleted_at IS NULL DO NOTHING;
CREATE UNIQUE INDEX members_active_email
ON members (email) WHERE deleted_at IS NULL;
CREATE TABLE members (
email text NOT NULL,
deleted_at timestamptz
);
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
- Which tables appear in this script?
- The references are `members`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.