Sub topic 6
Using EXCLUDED to reference the proposed row
This chapter assumes you can write INSERT ... ON CONFLICT (...) DO UPDATE and know what a unique constraint is. Both are covered in earlier chapters. Here the focus is the EXCLUDED row: what it contains, how to tell it apart from the existing row, and where it causes errors.
What EXCLUDED is
When an INSERT hits a conflict, PostgreSQL has two rows for the same key:
- The existing row, already stored in the table.
- The proposed row, which your
INSERTtried to add and which was rejected.
EXCLUDED is a special table name that exposes the proposed row inside DO UPDATE. The name comes from the fact that the row was excluded from insertion. It has the same columns as the target table, and you read it like any other table: EXCLUDED.quantity, EXCLUDED.sku.
The setup for the examples below is the same table used earlier in the tutorial:
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);Overwriting with EXCLUDED
The simplest use is to replace the stored value with the proposed one:
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 8)
ON CONFLICT (sku) DO UPDATE
SET quantity = EXCLUDED.quantity,
updated_at = now();The row for A-100 now has quantity = 8. If A-100 had not existed, the row would have been inserted with the same values. You wrote the values once, in the VALUES list, and EXCLUDED lets the update reuse them. Without it you would have to repeat the literal 8 in the SET clause, which breaks as soon as the values come from query parameters or a SELECT.
Combining the existing and proposed values
EXCLUDED is most useful when you need both rows at once. Inside DO UPDATE, the existing row is available under the target table's name:
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 3)
ON CONFLICT (sku) DO UPDATE
SET quantity = product_stock.quantity + EXCLUDED.quantity;With a stored quantity of 8, the result is 11. This is a counter pattern: each statement adds to a running total, and the new row is created if the key is new.
Qualify every column
If you write quantity without a qualifier on the right side of SET, PostgreSQL cannot tell which row you mean:
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 3)
ON CONFLICT (sku) DO UPDATE
SET quantity = quantity + EXCLUDED.quantity;
-- ERROR: column reference "quantity" is ambiguousThe column on the left of = is always the target table's column, so it never needs a qualifier. Columns on the right and in the WHERE clause must be qualified with either the table name (or alias) or EXCLUDED. Qualifying everything is a good habit.
Giving the target table an alias
Long table names make these expressions hard to read. You can alias the table in the INSERT clause:
INSERT INTO product_stock AS ps (sku, quantity)
VALUES ('A-100', 3)
ON CONFLICT (sku) DO UPDATE
SET quantity = ps.quantity + EXCLUDED.quantity;Once you add an alias, the original table name is no longer usable in that statement. Writing product_stock.quantity here would fail. You cannot alias EXCLUDED.
What EXCLUDED contains
EXCLUDED holds the row as it would have been inserted. That has a few consequences.
| Situation | What `EXCLUDED` contains |
|---|---|
| Column listed in the `INSERT` | The value you supplied |
| Column omitted from the `INSERT` | The column's default value, such as `now()` for `updated_at` |
| `BEFORE INSERT` trigger changes the row | The row after the trigger ran |
| Column with a generated or identity value | The value that would have been assigned |
The second row has a practical use. If you omit updated_at from the column list, EXCLUDED.updated_at is the column default, so you can copy it instead of calling now() a second time:
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 12)
ON CONFLICT (sku) DO UPDATE
SET quantity = EXCLUDED.quantity,
updated_at = EXCLUDED.updated_at;Both approaches give a current timestamp. The EXCLUDED form keeps the default in one place, the table definition. If you later change the default, the upsert follows it.
Row-level BEFORE INSERT triggers run on the proposed row before the conflict check, so they fire even when the row ends up updating an existing one. EXCLUDED reflects whatever the trigger did to the row. A BEFORE UPDATE trigger also fires for the update path.
Updating several columns at once
When most columns should take the proposed values, listing each assignment gets long. PostgreSQL accepts the row-constructor form of SET:
INSERT INTO product_stock (sku, quantity, updated_at)
VALUES ('A-100', 20, now())
ON CONFLICT (sku) DO UPDATE
SET (quantity, updated_at) = (EXCLUDED.quantity, EXCLUDED.updated_at);You must still name each column. There is no EXCLUDED.* shorthand that means "update everything". This is deliberate: you should decide which columns an upsert may overwrite. The key columns, and anything like a created_at timestamp, should usually be left out of SET.
Using EXCLUDED in the WHERE clause
EXCLUDED is also available in the WHERE clause of DO UPDATE, where it decides whether the update happens at all. A common case is "last write wins, but only if the incoming data is newer":
INSERT INTO product_stock (sku, quantity, updated_at)
VALUES ('A-100', 40, '2026-11-27 20:00:00+00')
ON CONFLICT (sku) DO UPDATE
SET quantity = EXCLUDED.quantity,
updated_at = EXCLUDED.updated_at
WHERE EXCLUDED.updated_at > product_stock.updated_at
RETURNING sku, quantity, updated_at;If the stored updated_at is later than the proposed one, the WHERE is false. The row is left alone and RETURNING yields nothing for it. This protects against stale messages that arrive out of order, for example from a queue that does not guarantee ordering.
Batch upserts and EXCLUDED
With several rows in one statement, PostgreSQL evaluates EXCLUDED once per conflicting row, so each stored row sees its own proposed row:
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 1), ('C-300', 7), ('D-400', 2)
ON CONFLICT (sku) DO UPDATE
SET quantity = product_stock.quantity + EXCLUDED.quantity;A-100 is incremented by 1. C-300 and D-400 are inserted if new, or incremented if they already exist. You do not write a loop, and the SET clause stays the same for every row.
The limit is that one statement may touch a given key only once. If two proposed rows share a key, the second would update a row the same statement already changed, and PostgreSQL raises ON CONFLICT DO UPDATE command cannot affect row a second time. Aggregate the duplicates with GROUP BY first, as shown in the batch chapter. This applies when the duplicate rows hit the same key, even if the stored row did not exist beforehand.
Evaluation order within SET
All expressions in SET are evaluated against the row as it was before the update, the same as in a plain UPDATE. Assignments do not see each other's results:
CREATE TABLE stock_audit (
sku text PRIMARY KEY,
quantity integer NOT NULL,
prev_quantity integer
);
INSERT INTO stock_audit (sku, quantity)
VALUES ('A-100', 10);
INSERT INTO stock_audit (sku, quantity)
VALUES ('A-100', 15)
ON CONFLICT (sku) DO UPDATE
SET prev_quantity = stock_audit.quantity,
quantity = EXCLUDED.quantity;After this runs, prev_quantity is 10 and quantity is 15. The order of the two assignments does not matter, because stock_audit.quantity in the first one still refers to the stored value of 10.
Where EXCLUDED is not available
EXCLUDED exists only in the DO UPDATE clause (in SET and WHERE). Three places where people expect it to work:
DO NOTHING: there is noSETorWHEREto use it in.RETURNING: this clause sees the final row, either the newly inserted row or the updated one. It cannot see the rejected proposed row.- The conflict target's index predicate: the
WHEREafterON CONFLICT (col)chooses an index and only accepts conditions on the target table's columns. It is a different clause from theWHEREafterDO UPDATE SET.
Common mistakes
- Unqualified columns on the right of
SET. This gives the "ambiguous" error shown earlier. Qualify with the table name, alias, orEXCLUDED. - Using the table name after aliasing. Once you write
INSERT INTO product_stock AS ps, onlypsis valid. - Overwriting key or audit columns. Copying every column from
EXCLUDED, including acreated_at, replaces the original creation time with the time of the latest write. - Expecting the sum of duplicates in one batch. The
EXCLUDEDrow is per proposed row. Two proposals for one key cause an error, not a combined total. - Forgetting that omitted columns are defaults.
EXCLUDED.updated_atis the default, not the stored value. Copy a column fromEXCLUDEDonly when you actually want the default or supplied value.
Summary
EXCLUDEDis the proposed row, available only inDO UPDATE'sSETandWHEREclauses.- The existing row is reached through the table name, or through the alias if you gave one.
- Omitted columns appear in
EXCLUDEDas their defaults, andBEFORE INSERTtriggers are reflected. - All
SETexpressions read the old row. Qualify every column on the right-hand side. - Each key may be proposed only once per statement.
Exercise
A table page_views (page text PRIMARY KEY, views bigint NOT NULL, first_seen timestamptz NOT NULL DEFAULT now(), last_seen timestamptz NOT NULL DEFAULT now()) receives batches of counts. Write an upsert for the page /home with 25 new views that adds the 25 to the stored count, updates last_seen, and leaves first_seen untouched.
Show answer
INSERT INTO pageviews (page, views)
VALUES ('/home', 25)
ON CONFLICT (page) DO UPDATE
SET views = pageviews.views + EXCLUDED.views,
lastseen = EXCLUDED.lastseen;
The last_seen column is omitted from the INSERT, so EXCLUDED.lastseen is its default, now(). `firstseen` does not appear in SET, so the original value is kept. The right side of the views assignment is qualified with both the table name and EXCLUDED.
Exercise
Why does this statement fail, and how do you fix it? INSERT INTO product_stock (sku, quantity) VALUES ('A-100', 2) ON CONFLICT (sku) DO UPDATE SET quantity = quantity + 2;
Show answer
The quantity on the right side of the assignment is ambiguous in a DO UPDATE clause, because both the existing row and EXCLUDED have a column with that name. PostgreSQL reports: column reference "quantity" is ambiguous. Qualify it as productstock.quantity (or use EXCLUDED.quantity + productstock.quantity if you want the proposed value instead of the literal 2).
Exercise
You upsert sensor readings and want the stored row to change only when the incoming reading has a later taken_at than the stored one. Which clause do you use, and what does RETURNING produce for a reading that is older?
Show answer
Add WHERE EXCLUDED.takenat > readings.takenat after the SET list of DO UPDATE. For an older reading the WHERE is false, so the row is not updated and RETURNING produces no row for it.