Sub topic 1
Why upserts need a unique constraint
An upsert inserts a row, or changes the existing row if one with the same key is already there, in one atomic statement. PostgreSQL spells this INSERT ... ON CONFLICT. The statement has to decide what "the same key" means, and a unique constraint or unique index is the only thing that can define it. This chapter explains why, what PostgreSQL accepts as that definition, and what goes wrong when the definition is missing.
Prerequisites
This chapter assumes you can:
- Write basic
SELECT,INSERT, andUPDATEstatements. - Explain what a primary key and a
UNIQUEconstraint do. - Run statements in
psqlor another PostgreSQL client. - Use PostgreSQL 15 or later to run every example, including the
NULLS NOT DISTINCToption shown near the end.ON CONFLICTitself works from PostgreSQL 9.5.
Examples use a product_stock table that tracks how many units of each product are on hand.
The problem an upsert solves
Suppose a nightly job loads stock counts from a warehouse feed. Some SKUs are new and some already exist. A common first attempt looks like this:
- Run
SELECTto see whether the SKU exists. - If it does, run
UPDATE. - If it does not, run
INSERT.
On a single connection this works. With two connections it fails, because the check and the write are separate steps and other sessions can act between them.
The diagram shows a race condition: two sessions each decide based on a fact (the row is absent) that stops being true before they act. Wrapping both steps in a transaction does not fix this at the default READ COMMITTED isolation level. Both sessions can still read "no row" and then both insert.
The only reliable guard in this sequence is the unique constraint, which rejected the second insert. An upsert moves that guard into the statement. PostgreSQL attempts the insert, and if the unique check reports a conflict, it takes the alternative action you chose instead of raising an error.
Starting point: the constraint that raises the error
Here is the table from the previous example, with a primary key on sku:
CREATE TABLE product_stock (
sku text PRIMARY KEY,
quantity integer NOT NULL,
updated_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO product_stock (sku, quantity) VALUES ('A-100', 5);
-- Running the INSERT a second time fails with a unique violation
-- on the primary key product_stock_pkey.The second run fails because the primary key is backed by a unique index named product_stock_pkey. When PostgreSQL inserts a row, it adds an entry to every index on the table. For a unique index, the insertion first checks whether an equal key is already present. If one is, the insert fails with SQLSTATE 23505.
ON CONFLICT hooks into exactly this check. It does not scan the table for matching rows. It asks the unique index whether the key is already present, and the answer decides which action runs.
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 5)
ON CONFLICT (sku) DO NOTHING;This statement runs without an error even though A-100 exists. The details of DO NOTHING and DO UPDATE come in later chapters. For now, the point is that the clause (sku) names columns that must be covered by a unique index.
What "conflict" means
A conflict is a violation of a unique constraint or unique index (or, for DO NOTHING only, an exclusion constraint). Nothing else counts. These do not trigger ON CONFLICT:
NOT NULLviolations.CHECKconstraint violations.- Foreign key violations.
If an upsert proposes NULL for a NOT NULL column, the statement still fails. ON CONFLICT handles key collisions only.
What counts as a unique constraint
Several objects can serve as the definition of a duplicate:
| Object | Example | Usable as an arbiter |
|---|---|---|
| Primary key | `PRIMARY KEY (sku)` | Yes |
| Unique constraint | `UNIQUE (email)` | Yes |
| Unique index | `CREATE UNIQUE INDEX ... ON t (email)` | Yes |
| Partial unique index | `CREATE UNIQUE INDEX ... WHERE deleted_at IS NULL` | Yes, with a matching predicate |
| Unique index on an expression | `CREATE UNIQUE INDEX ... ON t (lower(email))` | Yes, with the same expression |
| Non-unique index | `CREATE INDEX ... ON t (sku)` | No |
| Exclusion constraint | `EXCLUDE USING gist (...)` | `DO NOTHING` only, and not by column list |
| Deferrable unique constraint | `UNIQUE (sku) DEFERRABLE` | No |
The index chosen to detect the conflict is called the arbiter index. A primary key constraint and a UNIQUE constraint are both implemented as unique indexes, so the distinction between "constraint" and "unique index" matters little here. Choosing among several arbiters is the topic of the next chapters.
What happens without one
Consider a table that has no key at all:
CREATE TABLE stock_no_key (
sku text,
quantity integer NOT NULL
);
INSERT INTO stock_no_key (sku, quantity)
VALUES ('A-100', 5)
ON CONFLICT (sku) DO NOTHING;
-- ERROR: there is no unique or exclusion constraint matching
-- the ON CONFLICT specificationPostgreSQL refuses the statement while planning it. It looks for a unique index whose columns match (sku), finds none, and stops. This error is helpful. It tells you the table cannot define a duplicate, so no upsert is possible.
Now a subtler case. DO NOTHING with no conflict target is legal on any table:
INSERT INTO stock_no_key (sku, quantity)
VALUES ('A-100', 5)
ON CONFLICT DO NOTHING;
INSERT INTO stock_no_key (sku, quantity)
VALUES ('A-100', 5)
ON CONFLICT DO NOTHING;
SELECT count(*) FROM stock_no_key;
-- count: 2Both inserts succeed and the table holds two rows for A-100. The statement looks like a safe upsert, but with no unique index there is nothing that can conflict, so the clause never fires. This is the more dangerous failure, because no error warns you.
A non-unique index is not enough
Adding an ordinary index to speed up lookups does not help:
CREATE INDEX stock_no_key_sku_idx ON stock_no_key (sku);
INSERT INTO stock_no_key (sku, quantity)
VALUES ('A-100', 5)
ON CONFLICT (sku) DO NOTHING;
-- ERROR: there is no unique or exclusion constraint matching
-- the ON CONFLICT specificationThe index finds rows quickly, but it makes no promise that a key appears only once. Only a unique index can both detect a duplicate and prevent a second copy from existing, and an upsert needs both properties. Fixing the table means cleaning existing duplicates first, because CREATE UNIQUE INDEX fails if duplicates are already present:
TRUNCATE stock_no_key;
CREATE UNIQUE INDEX stock_no_key_sku_uidx ON stock_no_key (sku);
INSERT INTO stock_no_key (sku, quantity)
VALUES ('A-100', 5)
ON CONFLICT (sku) DO NOTHING;
INSERT INTO stock_no_key (sku, quantity)
VALUES ('A-100', 5)
ON CONFLICT (sku) DO NOTHING;
SELECT count(*) FROM stock_no_key;
-- count: 1In real systems you would remove duplicates selectively, for example by keeping the newest row per key, rather than using TRUNCATE.
How the constraint makes the statement atomic
The unique index also removes the race from the first section. When two sessions insert the same key at once, the second one waits on the first to commit or roll back. This is how PostgreSQL handles it:
- If the first session commits, the second sees a real conflict and takes the
ON CONFLICTaction. - If the first session rolls back, the second session's insert proceeds normally.
Either way, exactly one row exists for the key, and the second session never reports a spurious unique violation. This guarantee belongs to the index, not to the SQL you wrote around it. A later chapter covers the concurrency details. What matters here is the dependency: remove the unique index and the guarantee disappears.
Constraints that quietly fail to match
A few situations pass the "there is a unique index" test in your head but fail in PostgreSQL's matching.
Column order and set
The conflict target must name the same set of columns as the unique index. Order does not matter, but membership does. With UNIQUE (sku, region), the target (sku) alone does not match, because the index treats the pair as the unit of uniqueness.
Partial and expression indexes
A partial unique index only covers rows that satisfy its predicate. The conflict target must repeat that predicate so PostgreSQL can infer the index. Likewise, an index on lower(email) is matched only by a target written as (lower(email)). The "Choosing a conflict target" chapter shows the syntax.
NULLs are distinct by default
In a unique index, NULL is not equal to NULL. Rows with a NULL in an indexed column never conflict with each other:
CREATE TABLE price (
sku text NOT NULL,
region text,
amount numeric NOT NULL,
UNIQUE (sku, region)
);
INSERT INTO price (sku, region, amount)
VALUES ('A-100', NULL, 10)
ON CONFLICT (sku, region) DO NOTHING;
INSERT INTO price (sku, region, amount)
VALUES ('A-100', NULL, 10)
ON CONFLICT (sku, region) DO NOTHING;
SELECT count(*) FROM price;
-- count: 2The constraint is valid and the arbiter matches, yet two rows exist, because (A-100, NULL) is never considered equal to itself. If you want NULL treated as a normal value, declare the constraint with NULLS NOT DISTINCT:
CREATE TABLE price_strict (
sku text NOT NULL,
region text,
amount numeric NOT NULL,
UNIQUE NULLS NOT DISTINCT (sku, region)
);This option requires PostgreSQL 15 or later. On older versions, make the column NOT NULL or use a unique index on coalesce(region, '') and target the same expression.
Deferrable constraints
A constraint declared DEFERRABLE can postpone its check until commit. ON CONFLICT must decide at insertion time, so it cannot use a deferrable unique constraint as its arbiter. If your table needs a deferrable constraint for other reasons, add a separate non-deferrable unique index on the same columns for the upsert to use.
Choosing where to put the constraint
The conflict definition should come from your data model, not from the query you happen to be writing. Ask what makes two rows "the same thing" in the business domain, and encode that as a constraint:
- Prefer an existing natural key such as
skuwhen it is stable and required. - Use a composite unique constraint when identity spans columns, such as
(sku, warehouse_id). - Use a partial unique index when identity applies only to some rows, such as active accounts.
- Do not add a unique constraint purely to make a query run if the data does not truly have that rule. The constraint will reject legitimate inserts later.
Summary of the dependency
An upsert needs a way to say "this key is already here". PostgreSQL gets that answer from a unique index, checked atomically at insertion time. Without such an index, ON CONFLICT (cols) is rejected, and ON CONFLICT DO NOTHING with no target silently never fires. With one, the statement is safe under concurrent writers in a way that SELECT followed by INSERT is not.
Exercise
A table account (id bigint PRIMARY KEY, email text NOT NULL) has no constraint on email. A developer runs INSERT INTO account (id, email) VALUES (2, '[email protected]') ON CONFLICT (email) DO NOTHING;. What happens, and what must change so that a second account with the same email is skipped instead?
Show answer
PostgreSQL rejects the statement with "there is no unique or exclusion constraint matching the ON CONFLICT specification", because no unique index covers email. The primary key on id does not count, since the conflict target names a different column. To fix it, remove or merge any existing duplicate emails, then run CREATE UNIQUE INDEX account_email_uidx ON account (email); (or add UNIQUE (email)). After that, the statement skips a row whose email already exists.
Exercise
A table has UNIQUE (sku, region) where region is nullable. An upsert with ON CONFLICT (sku, region) DO NOTHING is run twice with region set to NULL. How many rows exist afterwards, and how can the constraint be changed so only one remains?
Show answer
Two rows exist, because NULL is not equal to NULL in a unique index, so the two rows never conflict. Declaring the constraint as UNIQUE NULLS NOT DISTINCT (sku, region) (PostgreSQL 15 or later) makes NULLs compare as equal, so the second insert is skipped and one row remains.
Exercise
Why does wrapping a SELECT-then-INSERT sequence in a transaction not make it safe against concurrent writers at the default READ COMMITTED isolation level?
Show answer
Both sessions can run the SELECT before either has committed an insert, so both see no row and both decide to insert. The transaction does not stop the other session from acting between the check and the write. Only the unique index closes the gap, because it rejects or handles the second insert at the moment of insertion.