Sub topic 1
Why upserts need a unique constraint
An upsert inserts a row when its key is new, or changes an existing row when that key is already present. PostgreSQL implements this pattern with INSERT ... ON CONFLICT. The database can detect the conflict only when a constraint or index defines which values must be unique.
Prerequisites
You should know basic SELECT, INSERT, and UPDATE statements, primary keys, and unique constraints. You should also know how to run SQL in psql or another PostgreSQL client.
A unique rule identifies the conflict
A unique constraint is a database rule that prevents two rows from having the same value in one column or the same combination of values in several columns. A primary key is also unique, so it can identify a conflict.
A unique index can provide the same conflict-detection mechanism. PostgreSQL uses the index to find an existing row whose key matches the row being inserted.
| Database object | Example | Purpose |
|---|---|---|
| Primary key | `sku text PRIMARY KEY` | Identifies each row and prevents duplicate keys |
| Unique constraint | `UNIQUE (email)` | Prevents duplicate email values |
| Unique index | `CREATE UNIQUE INDEX ...` | Enforces uniqueness, possibly for selected rows |
Consider a stock table where each stock-keeping unit, or SKU, must occur once:
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);The primary key creates a unique rule for sku. A second plain insert with the same SKU fails:
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 5);
-- ERROR: duplicate key value violates unique constraint
-- "product_stock_pkey"The error is useful because it protects the data. However, an application often wants to treat an existing SKU as a normal condition. ON CONFLICT lets the statement choose what to do instead of raising the duplicate-key error.
How PostgreSQL finds the conflict
The conflict target tells PostgreSQL which unique rule to use. The simplest form names one or more columns:
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 5)
ON CONFLICT (sku) DO NOTHING;PostgreSQL checks the unique rule for sku. If no row has that SKU, it inserts the row. If a row already has that SKU, DO NOTHING skips the proposed row.
Without a matching unique rule, PostgreSQL cannot use (sku) as a conflict target:
CREATE TABLE log_entry (
event_name text,
created_at timestamptz
);
INSERT INTO log_entry (event_name, created_at)
VALUES ('login', now())
ON CONFLICT (event_name) DO NOTHING;
-- ERROR: there is no unique or exclusion constraint matching
-- the ON CONFLICT specificationevent_name is not unique in this table. PostgreSQL has no safe way to decide which existing row represents the conflict.
You can also name a unique constraint directly:
CREATE TABLE account (
account_id bigint PRIMARY KEY,
email text NOT NULL,
CONSTRAINT account_email_key UNIQUE (email)
);
INSERT INTO account (account_id, email)
VALUES (1, '[email protected]')
ON CONFLICT ON CONSTRAINT account_email_key
DO NOTHING;Naming the constraint can make the statement clear and avoids repeating a multi-column key. It also ties the statement to that constraint name, so renaming or replacing the constraint requires updating the SQL.
Partial unique indexes
A partial unique index enforces uniqueness only for rows matching a predicate. For example, an application may allow an email to be reused after an account is soft-deleted:
CREATE UNIQUE INDEX account_active_email_idx
ON account (email)
WHERE deleted_at IS NULL;The conflict target must include the same predicate so PostgreSQL can infer this index:
INSERT INTO account (account_id, email, deleted_at)
VALUES (2, '[email protected]', NULL)
ON CONFLICT (email) WHERE deleted_at IS NULL
DO NOTHING;This protects active accounts while allowing multiple deleted accounts with the same email.
A unique constraint is therefore more than an optimization. It is the correctness boundary that makes an upsert atomic. Without it, two concurrent transactions could both observe that a key is absent and both insert a row.
Exercise
Why does ON CONFLICT (sku) fail when sku has no primary key, unique constraint, or suitable unique index?
Show answer
PostgreSQL has no uniqueness rule to identify which existing row conflicts with the proposed sku, so it cannot perform conflict handling safely.