Sub topic 4
Skipping duplicates with `DO NOTHING`
This chapter assumes that you know basic SELECT, INSERT, and UPDATE statements, primary keys, unique constraints, and how to run PostgreSQL statements in psql or another client.
A duplicate is a new row whose values match a uniqueness rule for a row already stored in the table. INSERT ... ON CONFLICT DO NOTHING tells PostgreSQL to ignore that proposed row instead of raising a unique-violation error.
Why a conflict can be detected
PostgreSQL needs a unique constraint or unique index to identify a conflict. A primary key is also a uniqueness rule, so it can detect duplicates.
Consider this table:
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 sku column is the primary key. PostgreSQL therefore allows only one row with the value A-100.
A plain second insert fails:
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 5);The client receives a unique-violation error. The failed statement does not silently choose between the old row and the new row. You must request duplicate-skipping behavior explicitly.
The `DO NOTHING` form
Add ON CONFLICT DO NOTHING to skip a row that conflicts with any usable uniqueness rule:
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 5)
ON CONFLICT DO NOTHING;If A-100 already exists, PostgreSQL makes no change and does not raise an error. If it does not exist, PostgreSQL inserts the row.
This behavior is useful when the first writer should win. For example, an application might create a user record only if another process has not already created the same email address.
You can name the conflict target to document which uniqueness rule matters:
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 5)
ON CONFLICT (sku) DO NOTHING;The column list must identify a unique constraint or unique index. It does not mean “find any row where sku happens to be equal” without a uniqueness rule.
| Form | Behavior |
|---|---|
| `ON CONFLICT DO NOTHING` | Skip a conflict found through any applicable unique rule |
| `ON CONFLICT (sku) DO NOTHING` | Skip a conflict identified by the uniqueness rule for `sku` |
| `ON CONFLICT ON CONSTRAINT name DO NOTHING` | Skip a conflict identified by a named constraint |
What remains unchanged
DO NOTHING does not update the existing row. It also does not add values to the existing row.
After the following statement, the stored quantity remains whatever it was before:
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 3)
ON CONFLICT (sku) DO NOTHING;If the existing row contains quantity 5, it still contains 5. The proposed quantity 3 is discarded. Use DO UPDATE when a conflict should change the existing row.
Partial unique indexes
A partial unique index enforces uniqueness only for rows that satisfy a predicate. A predicate is a condition such as deleted_at IS NULL.
CREATE TABLE app_user (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email text NOT NULL,
name text NOT NULL,
deleted_at timestamptz
);
CREATE UNIQUE INDEX app_user_email_active_idx
ON app_user (email)
WHERE deleted_at IS NULL;This index allows multiple deleted rows with the same email, but only one active row. The conflict target must include the same predicate:
INSERT INTO app_user (email, name)
VALUES ('[email protected]', 'Ada')
ON CONFLICT (email) WHERE deleted_at IS NULL
DO NOTHING;Without the predicate, PostgreSQL may not be able to infer the intended partial index.
Concurrency behavior
The uniqueness check happens inside the INSERT statement. This is safer than first running a SELECT and then deciding whether to insert:
- Two sessions can both run the
SELECTbefore either inserts. - Both sessions can conclude that the key is free.
- One insert succeeds, and the other receives a duplicate-key error.
With ON CONFLICT DO NOTHING, PostgreSQL coordinates the uniqueness check with concurrent writers. One session inserts the row, while the other skips its conflicting proposal.
Checking whether a row was inserted
RETURNING reports rows that the statement inserted. A skipped row is not returned:
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 5)
ON CONFLICT (sku) DO NOTHING
RETURNING sku, quantity;If the insert succeeds, the result contains one row. If the key already exists and the conflict is skipped, the result is empty. An application can use this distinction to decide whether it created the row or whether another row already owned the key.
Exercise
What happens to an existing product_stock row when an insert with the same sku uses ON CONFLICT (sku) DO NOTHING?
Show answer
The existing row is unchanged, the proposed row is discarded, and the statement completes without a unique-violation error.