Sub topic 4
Skipping duplicates with DO NOTHING
This chapter assumes you can write basic SELECT, INSERT and UPDATE statements, know what primary keys and unique constraints are, and can run statements in psql or another PostgreSQL client. Earlier chapters covered why upserts need a unique constraint and how a plain INSERT fails on a duplicate key. Here you will use ON CONFLICT DO NOTHING, the simplest way to make an insert tolerate duplicates.
What DO NOTHING does
ON CONFLICT DO NOTHING tells PostgreSQL to skip a proposed row when inserting it would violate a unique constraint or unique index. The statement does not raise an error, and the existing row is left exactly as it was.
Set up the table from the previous chapter and give it one row:
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);Now propose a row with the same sku, but with DO NOTHING:
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 99)
ON CONFLICT (sku) DO NOTHING;psql reports the command tag INSERT 0 0. The first number is an object ID that is always 0 in modern PostgreSQL. The second number is the count of rows actually inserted. Zero means the row was skipped. The stored quantity for A-100 is still 5, not 99.
flowchart TD
A[Proposed row] --> B{Does a row with the same key already exist?}
B -- No --> C[Insert the row]
B -- Yes --> D[Skip the row silently]
C --> E[Counted in the INSERT row count]
D --> F[Not counted, not returned]The diagram above is wrapped as a diagram block below.
The conflict target is optional here
For DO UPDATE, PostgreSQL requires a conflict target. For DO NOTHING you can leave it out:
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 99)
ON CONFLICT DO NOTHING;Without a target, a conflict on any unique constraint or unique index causes a skip. With a target, only a conflict on the index that the target identifies causes a skip. A violation of any other unique index still raises an error. This difference matters when a table has more than one unique constraint.
The target can take three forms:
| Form | Example | Use when |
|---|---|---|
| Column list | `ON CONFLICT (sku)` | A unique index covers exactly those columns |
| Column list with predicate | `ON CONFLICT (email) WHERE deleted_at IS NULL` | The index is a partial unique index |
| Constraint name | `ON CONFLICT ON CONSTRAINT product_stock_pkey` | You prefer to name the constraint directly |
PostgreSQL uses the target to pick the arbiter index, the index that decides whether a row conflicts. The column-list form is usually preferred because it survives a constraint being renamed.
Only the named conflict is skipped
Consider a table with two separate unique constraints:
CREATE TABLE account (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email text NOT NULL UNIQUE,
handle text NOT NULL UNIQUE
);
INSERT INTO account (email, handle) VALUES ('[email protected]', 'ada');Skipping on the email column works as expected:
INSERT INTO account (email, handle)
VALUES ('[email protected]', 'ada2')
ON CONFLICT (email) DO NOTHING;
-- INSERT 0 0A different row that collides on handle is not covered by that target:
INSERT INTO account (email, handle)
VALUES ('[email protected]', 'ada')
ON CONFLICT (email) DO NOTHING;
-- ERROR: duplicate key value violates unique constraint "account_handle_key"If you want either collision to be skipped, omit the target:
INSERT INTO account (email, handle)
VALUES ('[email protected]', 'ada')
ON CONFLICT DO NOTHING;
-- INSERT 0 0What DO NOTHING does not ignore
DO NOTHING handles unique violations and, when no target is given, exclusion constraint violations. It does not suppress other errors. These still abort the statement:
- A
NOT NULLviolation, for example insertingNULLintoquantity. - A
CHECKconstraint failure. - A foreign key violation.
- A type conversion error, such as
'abc'for an integer column.
If one row in a multi-row statement fails for one of these reasons, the whole statement fails and no rows are inserted. DO NOTHING is not a general "ignore bad rows" switch.
Multi-row inserts
Because each row is tested independently, you can load a batch where some rows already exist:
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 99), ('C-300', 7)
ON CONFLICT (sku) DO NOTHING;
-- INSERT 0 1A-100 is skipped and C-300 is inserted. The count is 1.
Duplicates inside the same statement are also fine with DO NOTHING:
INSERT INTO product_stock (sku, quantity)
VALUES ('D-400', 1), ('D-400', 2)
ON CONFLICT (sku) DO NOTHING;
-- INSERT 0 1The first D-400 row is inserted and the second is skipped, so the stored quantity is 1. Rows are processed in the order given, so the earliest wins. This is different from DO UPDATE, which fails when one statement proposes the same key twice. That error is covered in a later chapter.
Reading results with RETURNING
RETURNING outputs only rows that were actually inserted. Skipped rows produce nothing:
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 99), ('E-500', 4)
ON CONFLICT (sku) DO NOTHING
RETURNING sku, quantity;The result contains one row, for E-500. Nothing is returned for A-100, so you cannot tell from the result alone whether the key already existed or whether something else went wrong. In application code, an empty result set means "already existed" only when the statement succeeded.
A common need is to get the row's id whether it was inserted or already present. DO NOTHING alone cannot do that, but a common workaround combines it with a fallback SELECT:
WITH ins AS (
INSERT INTO account (email, handle)
VALUES ('[email protected]', 'ada')
ON CONFLICT (email) DO NOTHING
RETURNING id
)
SELECT id FROM ins
UNION ALL
SELECT id FROM account WHERE email = '[email protected]'
LIMIT 1;If the insert happened, ins supplies the id. If it was skipped, the second branch finds the existing row. LIMIT 1 stops the query as soon as one row is available.
Behavior under concurrency
DO NOTHING is safe against concurrent writers in a way that "SELECT, then INSERT if missing" is not. In the check-then-insert approach, two sessions can both see no row and both attempt the insert, and one of them fails with a unique violation.
With ON CONFLICT, the check and the insert are part of one statement. If another transaction has inserted the same key but has not yet committed, your statement waits for that transaction to finish:
- If the other transaction commits, your row is skipped.
- If the other transaction rolls back, your row is inserted.
Either way, no unique violation error reaches you for the arbiter index. The next chapters on DO UPDATE and concurrency return to this in more detail.
Side effects of skipped rows
Skipping a row is cheap, but not free of side effects.
Sequences still advance
Default values and identity columns are evaluated before the conflict is detected. A skipped row therefore consumes a value from the sequence behind an identity or serial column. Inserting many duplicates into the account table leaves gaps in id. Gaps are normal in PostgreSQL and do not indicate a problem, but do not rely on ids being contiguous. If you load millions of mostly duplicate rows into a table with an integer identity column, the sequence can run out of values much sooner than the row count suggests.
Triggers
BEFORE INSERT row triggers fire for every proposed row, including rows that are then skipped. AFTER INSERT row triggers fire only for rows that were actually inserted. Side effects placed in a BEFORE INSERT trigger can therefore happen for rows that never reach the table.
Dead tuples
A skipped row in a conflict that was found by the index check normally leaves nothing behind. In a race, however, PostgreSQL inserts the heap tuple speculatively and may have to abandon it when another session wins. Abandoned tuples are dead tuples that VACUUM later cleans up. This is a minor cost for an occasional collision, but a workload that proposes mostly duplicates under heavy concurrency can generate noticeable bloat.
When DO NOTHING is the right tool
Use DO NOTHING when the first writer should win and later duplicates carry no new information. Typical cases are:
- Idempotent event ingestion, where a retried message must not create a second record.
- Seeding reference data in migrations that may run more than once.
- Loading batches that overlap with data already in the table.
Use DO UPDATE when the later value should replace or combine with the stored one. If you find yourself running a DO NOTHING insert followed by an UPDATE, that is a sign that a single DO UPDATE statement fits better.
Summary
ON CONFLICT DO NOTHING skips rows that would violate a unique constraint and reports the number of rows actually inserted. A named target limits skipping to one index, and no target skips on any unique conflict. Other constraint violations still raise errors. RETURNING shows inserted rows only. Skipped rows still consume sequence values and fire BEFORE INSERT triggers.
Exercise
A table subscriber has email text UNIQUE and phone text UNIQUE. You run INSERT INTO subscriber (email, phone) VALUES ('[email protected]', '555-0100') ON CONFLICT (email) DO NOTHING RETURNING email;. The email is new, but the phone number already belongs to another subscriber. What happens, and how would you change the statement so the row is skipped instead?
Show answer
The statement fails with a unique violation on the phone constraint (named subscriber_phone_key by default), because the conflict target (email) only covers the email index and no row is inserted. To skip the row on either collision, remove the target and write ON CONFLICT DO NOTHING. The trade-off is that a phone collision for a new email is then dropped silently, so keep the target if you want to be told about it.
Exercise
You run INSERT INTO product_stock (sku, quantity) VALUES ('A-100', 1), ('F-600', 2), ('F-600', 3) ON CONFLICT (sku) DO NOTHING RETURNING sku, quantity; against a table that already contains A-100. Which rows are returned, and what is the command tag?
Show answer
One row is returned: F-600 with quantity 2. A-100 is skipped because it already exists, and the second F-600 is skipped because the first one was just inserted by the same statement. The command tag is INSERT 0 1.