Sub topic 9
Upserting many rows in one statement
This chapter assumes you can already write a single-row INSERT ... ON CONFLICT DO UPDATE and use EXCLUDED. It also assumes you have a unique constraint to use as the conflict target. The examples use the product_stock table from earlier chapters:
CREATE TABLE IF NOT EXISTS product_stock (
sku text PRIMARY KEY,
quantity integer NOT NULL,
updated_at timestamptz NOT NULL DEFAULT now()
);Loading rows one statement at a time is slow. Each statement costs a network round trip and a parse and plan step, and each commit may wait for a disk flush. One statement that upserts many rows removes most of that overhead. It also makes the whole batch atomic: either every row is applied or none is.
The basic multi-row upsert
INSERT accepts several rows in VALUES. ON CONFLICT is evaluated once per proposed row, and EXCLUDED refers to the row currently being processed.
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 5),
('B-200', 2),
('C-300', 9)
ON CONFLICT (sku) DO UPDATE
SET quantity = EXCLUDED.quantity,
updated_at = now();Rows whose sku is new are inserted. Rows whose sku already exists are updated. If any row fails for another reason, such as a NOT NULL violation, the whole statement fails and nothing is changed.
The same key twice in one statement
The batch can contain the same key more than once. What happens depends on the conflict action.
With DO NOTHING, the second occurrence conflicts with the first row the statement just inserted and is skipped. The first occurrence wins, and no error is raised.
With DO UPDATE, PostgreSQL refuses to modify one row twice in a single command:
-- Fails: the same sku is proposed twice in one statement.
INSERT INTO product_stock (sku, quantity)
VALUES ('B-200', 1), ('B-200', 2)
ON CONFLICT (sku) DO UPDATE SET quantity = EXCLUDED.quantity;
-- ERROR: ON CONFLICT DO UPDATE command cannot affect row a second time
-- HINT: Ensure that no rows proposed for insertion within the same command have duplicate constrained values.The error can appear even when B-200 does not exist yet. The first proposed row is inserted, the second conflicts with it, and DO UPDATE would then have to change a row that this same command created. The rule exists because the order in which the rows of one statement are processed is not something you should depend on.
You have to decide what the duplicates mean before the statement runs. The two usual answers are combining them or keeping one.
Combine duplicates
If the duplicates are separate increments, add them up first:
INSERT INTO product_stock (sku, quantity)
SELECT sku, sum(quantity)
FROM (VALUES ('B-200', 1), ('B-200', 2)) AS v(sku, quantity)
GROUP BY sku
ON CONFLICT (sku) DO UPDATE SET quantity = EXCLUDED.quantity;Each sku now appears once, with quantity 3.
Keep the latest duplicate
If the duplicates are successive readings of the same value, keep the newest one. DISTINCT ON does this when you have a column that defines "newest". This example uses a staging table with an id that grows with arrival order:
CREATE TEMP TABLE stock_feed (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
sku text NOT NULL,
quantity integer NOT NULL
);
INSERT INTO stock_feed (sku, quantity)
VALUES ('B-200', 1), ('B-200', 2), ('C-300', 7);
INSERT INTO product_stock (sku, quantity)
SELECT DISTINCT ON (sku) sku, quantity
FROM stock_feed
ORDER BY sku, id DESC
ON CONFLICT (sku) DO UPDATE
SET quantity = EXCLUDED.quantity,
updated_at = now();ORDER BY sku, id DESC makes DISTINCT ON keep the highest id for each sku. The result is B-200 with quantity 2 and C-300 with quantity 7.
Ways to supply the batch
VALUES is not the only source of rows. Any query can feed an INSERT.
| Source | Good for | Watch out for |
|---|---|---|
| Multi-row `VALUES` | Small batches built by hand or by an ORM | Each value is a bound parameter, and the protocol allows at most 65535 per statement |
| `INSERT ... SELECT` from a staging table | Large loads, data that needs cleanup first | You must create and clean up the staging table |
| `unnest` over arrays | Application code sending a variable-size batch | Arrays must have the same length and be cast to the right types |
| `COPY` into staging, then upsert | Very large loads | Two steps, and the upsert still must handle duplicates |
Passing arrays with unnest
With unnest, the statement always uses one parameter per column, no matter how many rows it carries. That keeps you under the parameter limit and lets the same statement text be reused. Here is the statement with literal arrays so you can run it in psql:
INSERT INTO product_stock (sku, quantity)
SELECT *
FROM unnest(
ARRAY['A-100', 'B-200', 'D-400']::text[],
ARRAY[5, 2, 11]::integer[]
) AS v(sku, quantity)
ON CONFLICT (sku) DO UPDATE
SET quantity = EXCLUDED.quantity,
updated_at = now();In application code, replace each ARRAY[...] with a bound parameter such as $1::text[] and $2::integer[]. The multi-argument form of unnest in FROM walks the arrays in step, so the first SKU pairs with the first quantity.
Reading results from a batch
RETURNING works on a batch and returns one row per inserted or updated row:
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 5), ('B-200', 2), ('E-500', 1)
ON CONFLICT (sku) DO UPDATE
SET quantity = EXCLUDED.quantity,
updated_at = now()
WHERE product_stock.quantity IS DISTINCT FROM EXCLUDED.quantity
RETURNING sku, quantity;Rows skipped by DO NOTHING, or filtered out by the WHERE clause on DO UPDATE, are not returned. If the application needs one result per input row, do not assume RETURNING provides it. Compare the returned keys against the input keys, or run a follow-up SELECT.
A common request is to learn which rows were inserted and which were updated. This expression is widely used:
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 5), ('F-600', 4)
ON CONFLICT (sku) DO UPDATE
SET quantity = EXCLUDED.quantity
RETURNING sku, (xmax = 0) AS inserted;xmax is a system column. For a freshly inserted row it is 0, and for an updated row it is not. This relies on an implementation detail rather than documented behavior, so treat it as a convenience for logging and diagnostics, not as a guarantee your logic depends on.
Locking, deadlocks, and batch size
Every row an upsert inserts or updates is locked until the transaction ends. Two concurrent transactions that upsert overlapping keys in opposite orders can each hold a lock the other needs. PostgreSQL detects this and aborts one of them with ERROR: deadlock detected.
Sorting the batch by the conflict key makes every writer take locks in the same order, which avoids this case. The ORDER BY sku in the earlier DISTINCT ON example does this as a side effect. For a plain VALUES list, sort the rows in the application before sending them.
Large batches have other costs:
- Locks are held for the whole statement and its transaction, so a very large upsert can block other writers for a long time.
- A failure on row 900,000 rolls back the previous 899,999 rows.
- Every updated row creates a new row version, so large updates add work for autovacuum.
A practical approach is to chunk the input into batches of a few thousand rows, sorted by key, each in its own transaction. Measure on your own hardware, because the best size depends on row width, indexes, and concurrency.
Several unique indexes on one table
The conflict target names exactly one arbiter index, or a set of columns that PostgreSQL maps to one. DO UPDATE only handles conflicts on that arbiter. If a proposed row also violates a different unique index, the statement fails with an ordinary unique violation:
CREATE TABLE sku_alias (
sku text PRIMARY KEY,
alias text NOT NULL UNIQUE
);
INSERT INTO sku_alias (sku, alias) VALUES ('A-100', 'apple');
-- Conflicts on sku, so the row is updated.
INSERT INTO sku_alias (sku, alias) VALUES ('A-100', 'apricot')
ON CONFLICT (sku) DO UPDATE SET alias = EXCLUDED.alias;
-- Conflicts on alias, which is not the target. This raises an error.
INSERT INTO sku_alias (sku, alias) VALUES ('B-200', 'apricot')
ON CONFLICT (sku) DO UPDATE SET alias = EXCLUDED.alias;In a batch, one such row aborts the whole statement. ON CONFLICT DO NOTHING without a target skips conflicts on any unique index, which is sometimes what you want for loading data that must be deduplicated on several keys.
Common errors in batch upserts
| Symptom | Cause | Fix |
|---|---|---|
| `ON CONFLICT DO UPDATE command cannot affect row a second time` | The batch proposes the same key twice | Merge with `GROUP BY` or `DISTINCT ON` |
| `deadlock detected` | Concurrent batches lock keys in different orders | Sort each batch by the conflict key |
| Unique violation on a different index | Conflict on an index that is not the arbiter | Handle that key separately, or use `DO NOTHING` with no target |
| `RETURNING` has fewer rows than the input | Rows were skipped by `DO NOTHING` or a `WHERE` filter | Compare keys, or query the table afterward |
| Too many bind parameters | `VALUES` list exceeds 65535 parameters | Use `unnest` or smaller chunks |
Exercise
A feed delivers rows (sku, quantity) with repeated SKUs, and each repeated row is a separate sale that should reduce stock. Write a single statement that applies a batch such as ('A-100', -1), ('A-100', -2), ('B-200', -4) to product_stock, adding the combined change to the existing quantity.
Show answer
Combine duplicates first, then add to the existing value: INSERT INTO productstock (sku, quantity) SELECT sku, sum(quantity) FROM (VALUES ('A-100', -1), ('A-100', -2), ('B-200', -4)) AS v(sku, quantity) GROUP BY sku ON CONFLICT (sku) DO UPDATE SET quantity = productstock.quantity + EXCLUDED.quantity, updated_at = now(); GROUP BY leaves one row per sku, which avoids the "cannot affect row a second time" error. The table name refers to the existing row and EXCLUDED to the combined proposed row. Note that a SKU that does not exist yet is inserted with the negative total.
Exercise
Two workers upsert overlapping sets of SKUs into product_stock in separate transactions. Occasionally one fails with "deadlock detected". What is the likely cause, and what is the simplest fix?
Show answer
The workers send their rows in different orders, so each can lock a row the other needs next. Sort every batch by the conflict key (sku) before sending it, so all workers take row locks in the same order. Smaller batches also shorten how long locks are held.
Exercise
An upsert with ON CONFLICT (sku) DO UPDATE ... WHERE product_stock.quantity IS DISTINCT FROM EXCLUDED.quantity RETURNING sku sends 100 rows and gets back 37 rows. Is something wrong?
Show answer
Not necessarily. RETURNING only yields rows that were inserted or actually updated. Rows whose existing quantity already equals the proposed quantity fail the WHERE test, are skipped, and are not returned. To confirm, compare the returned skus against the input skus.