Sub topic 9
Upserting Many Rows in One Statement
Assume you know SELECT, INSERT, and UPDATE, and that product_stock.sku is a primary key or has a unique constraint. A multi-row upsert sends several proposed rows to PostgreSQL in one statement. PostgreSQL checks each row against the unique index and either inserts it, skips it, or updates the matching row.
Insert several rows at once
Use a VALUES list when the input is already available as a small set of rows:
INSERT INTO product_stock (sku, quantity)
VALUES
('A-100', 5),
('B-200', 12),
('C-300', 4)
ON CONFLICT (sku) DO UPDATE
SET quantity = EXCLUDED.quantity,
updated_at = now()
RETURNING sku, quantity;For each sku, PostgreSQL does one of two things:
- Inserts a new row when the key does not exist.
- Updates the existing row when the key conflicts.
EXCLUDED represents the proposed row for the current input item. The table name, product_stock, represents the existing row.
The statement returns the rows that were inserted or updated. The order of rows in RETURNING should not be treated as the order of the input list.
Duplicate keys inside the batch
A common mistake is to repeat the same key in one VALUES list while using DO UPDATE:
-- This fails.
INSERT INTO product_stock (sku, quantity)
VALUES
('B-200', 1),
('B-200', 2)
ON CONFLICT (sku) DO UPDATE
SET quantity = EXCLUDED.quantity;PostgreSQL raises an error similar to:
ERROR: ON CONFLICT DO UPDATE command cannot affect row a second timeOne INSERT ... ON CONFLICT DO UPDATE statement cannot update the same target row twice. PostgreSQL stops instead of choosing an arbitrary value.
DO NOTHING has different behavior. If several proposed rows have the same conflicting key, PostgreSQL can skip the duplicate rows. However, skipping may not express your business rule. If the quantities represent separate stock events, you probably need to combine them first.
Merge duplicates before the upsert
Aggregate input rows by their key before applying ON CONFLICT:
INSERT INTO product_stock (sku, quantity)
SELECT sku, sum(quantity)
FROM (
VALUES
('B-200', 1),
('B-200', 2),
('C-300', 4)
) AS incoming(sku, quantity)
GROUP BY sku
ON CONFLICT (sku) DO UPDATE
SET quantity = product_stock.quantity + EXCLUDED.quantity,
updated_at = now()
RETURNING sku, quantity;The subquery changes the two B-200 rows into one row with a quantity of 3. The upsert then adds that quantity to the existing stock. This pattern is useful when each input row is an increment rather than a replacement.
The aggregation rule must match the meaning of the data:
| Input meaning | Pre-upsert operation |
|---|---|
| Each row adds stock | `sum(quantity)` |
| Each row is a replacement | Choose one row using a timestamp or priority |
| Duplicate rows are invalid | Reject or validate them before the statement |
Insert from a query
The source does not have to be a literal VALUES list. You can upsert rows selected from a staging table, a JSON expansion, or another query:
INSERT INTO product_stock (sku, quantity)
SELECT sku, sum(quantity)
FROM stock_import
GROUP BY sku
ON CONFLICT (sku) DO UPDATE
SET quantity = EXCLUDED.quantity,
updated_at = now();The SELECT must produce no more than one row for each conflict key when the statement uses DO UPDATE. If stock_import contains duplicate sku values, GROUP BY makes the input deterministic.
Batch size and results
Large batches reduce network round trips, but they consume more memory and can hold locks longer. Split very large imports into manageable batches when transaction duration or lock contention matters.
With DO UPDATE ... WHERE, a conflicting row that fails the condition is locked but not updated. It is not included in RETURNING. Therefore, the number of input rows can exceed the number of returned rows.
Exercise
Why must duplicate sku values be grouped before a batch ON CONFLICT DO UPDATE statement?
Show answer
The statement cannot update the same target row twice. Grouping produces one proposed row per sku, so PostgreSQL can apply one insert or update for each key.