Sub topic 9
Returning columns from joined tables with FROM and USING
UPDATE and DELETE can join to other tables while they change rows. PostgreSQL does this with UPDATE ... FROM and DELETE ... USING. In both statements the RETURNING list can read columns from those joined tables as well as from the target table. This chapter shows how that works, what it returns when joins match several rows, and where it stops working.
This chapter assumes you know basic joins, aliases, and the RETURNING syntax from earlier chapters. You should be able to run statements in psql or another PostgreSQL client.
Setup
The earlier examples used a single tasks table. Joins need two tables, so this chapter uses its own pair. Run this once in a scratch database.
CREATE TABLE projects (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL UNIQUE,
archived boolean NOT NULL DEFAULT false
);
CREATE TABLE work_items (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
project_id bigint NOT NULL REFERENCES projects (id),
title text NOT NULL,
status text NOT NULL DEFAULT 'open',
priority int NOT NULL DEFAULT 0
);
INSERT INTO projects (name, archived)
VALUES ('Alpha', false), ('Beta', true), ('Gamma', false);
INSERT INTO work_items (project_id, title)
VALUES (1, 'Draft spec'),
(1, 'Set up CI'),
(2, 'Write docs'),
(2, 'Fix login'),
(3, 'Plan launch');Identity values are assigned in order, so Alpha, Beta and Gamma get ids 1, 2 and 3. The work items get ids 1 to 5.
What the RETURNING list can see
A plain UPDATE has one table in scope. Adding a FROM clause brings more tables into scope for WHERE, for the SET expressions, and for RETURNING. DELETE does the same with USING.
The table below compares the three statements.
| Statement | Clause that adds tables | RETURNING can read joined tables? | Rows returned |
|---|---|---|---|
| `UPDATE` | `FROM` | Yes | One per updated target row |
| `DELETE` | `USING` | Yes | One per deleted target row |
| `INSERT ... SELECT` | `FROM` inside the `SELECT` | No | One per inserted row |
UPDATE ... FROM with RETURNING
This statement closes every open item that belongs to an archived project. It returns the project name next to each changed item.
UPDATE work_items AS w
SET status = 'closed'
FROM projects AS p
WHERE p.id = w.project_id
AND p.archived
RETURNING w.id, w.title, p.name AS project_name, w.status; id | title | project_name | status
----+------------+--------------+--------
3 | Write docs | Beta | closed
4 | Fix login | Beta | closedWithout the join in RETURNING, you would need a second query to learn which project each changed item belonged to. Row order is not guaranteed unless you wrap the statement in a CTE and sort the outer query.
Two rules apply to the names in the list:
w.statusis the value after the update.RETURNINGreports the new version of the target row.- If you give the target table an alias, you must use that alias in
RETURNING. AfterUPDATE work_items AS w, the namework_items.idis an error.
Returning with `*`
RETURNING * in UPDATE ... FROM returns all target columns first, followed by all columns from the FROM items. Both tables here have id and name-style columns, so the result can contain duplicate column names, which is awkward for client code. Prefer an explicit list with aliases, or use w.* to get only the target columns.
UPDATE work_items AS w
SET priority = priority + 1
FROM projects AS p
WHERE p.id = w.project_id
AND p.name = 'Alpha'
RETURNING w.*, p.name AS project_name;This returns every column of each updated work item plus one project column. Alpha has two items, so you get two rows. Their priority is now 1.
Updating from a list of values
A common bulk-update pattern joins the target to a VALUES list. RETURNING then confirms which input rows found a match.
UPDATE work_items AS w
SET priority = v.priority
FROM (VALUES (1, 5), (3, 2), (99, 7)) AS v (id, priority)
WHERE w.id = v.id
RETURNING w.id, w.title, w.priority; id | title | priority
----+------------+----------
1 | Draft spec | 5
3 | Write docs | 2The input row for id 99 matched nothing, so it produces no output. To find unmatched inputs, compare the number of rows returned with the number of rows you sent. Or collect the returned ids and compute the difference in application code.
In the SET clause, the left side of an assignment must be an unqualified column name (priority, not w.priority). The right side can use any in-scope name, so v.priority is fine.
What happens when the join matches several rows
UPDATE ... FROM has a rule that is easy to forget. If one target row matches several FROM rows, PostgreSQL updates that target row only once, using one of the matches. The documentation says which match is used is unspecified. RETURNING follows the same behavior: one output row per updated target row, not one per join match.
UPDATE projects AS p
SET archived = true
FROM work_items AS w
WHERE w.project_id = p.id
AND w.status = 'closed'
RETURNING p.id, p.name, w.id AS work_item_id;Beta has two closed items (ids 3 and 4). The statement returns one row for Beta. The work_item_id column is either 3 or 4, and you cannot rely on which. Only use joined-table columns in RETURNING when the join has at most one match per target row, or when you accept an arbitrary pick. If you need to be deterministic, put the join in a subquery that picks one row per key, for example with DISTINCT ON, and join to that.
Getting the old value with a self-join
Before PostgreSQL 18 introduced RETURNING OLD (covered in a later chapter), RETURNING could only show new target values. A self-join in FROM works around this. The FROM item reads the table as it was when the statement started, so its columns hold the old values.
UPDATE work_items AS w
SET status = 'closed'
FROM work_items AS old
WHERE old.id = w.id
AND w.id = 2
RETURNING w.id, old.status AS previous_status, w.status AS new_status; id | previous_status | new_status
----+-----------------+------------
2 | open | closedThe self-join matches each row to itself, so the one-match rule above is satisfied.
DELETE ... USING with RETURNING
DELETE takes extra tables through USING. The returned rows are the deleted target rows, and the list can also read from the USING tables.
DELETE FROM work_items AS w
USING projects AS p
WHERE w.project_id = p.id
AND p.name = 'Beta'
RETURNING w.id, w.title, p.name AS project; id | title | project
----+------------+---------
3 | Write docs | Beta
4 | Fix login | BetaIf a target row matches several USING rows, it is still deleted once and returned once. Unlike UPDATE, nothing here depends on which match is picked, as long as you only return target columns. If you return USING columns and the join is one-to-many, the same arbitrary-pick caveat applies.
A common use is cleanup that must record what was removed. Combine it with a data-modifying CTE, as in the earlier chapter, to write the joined values into an audit table in the same statement:
CREATE TABLE removed_items (
id bigint PRIMARY KEY,
title text NOT NULL,
project_name text NOT NULL
);
WITH gone AS (
DELETE FROM work_items AS w
USING projects AS p
WHERE w.project_id = p.id
AND p.name = 'Alpha'
RETURNING w.id, w.title, p.name AS project_name
)
INSERT INTO removed_items (id, title, project_name)
SELECT id, title, project_name FROM gone;The audit insert and the delete succeed or fail together.
Name clashes and ambiguity
When two joined tables share a column name, an unqualified reference in RETURNING fails with an "ambiguous column" error. Both work_items and projects have id, so this fails:
UPDATE work_items AS w
SET status = 'open'
FROM projects AS p
WHERE p.id = w.project_id
RETURNING id;Qualify every column in a joined statement, even where the name is unique today. A column added to the other table later could otherwise turn a working statement into an error.
What does not work
INSERT ... SELECT ... FROM other_table does not let RETURNING read other_table. The RETURNING list of an INSERT sees only the inserted target row. If you need source columns in the result, return the new keys and join in a second step. Alternatively, put the INSERT in a CTE and join its RETURNING output to the source in the outer query. That only works when the source and the new rows share a column you can match on, such as a unique title.
Other edge cases:
- If the join matches no target rows, the statement changes nothing and returns zero rows. This is not an error.
- A
FROMorUSINGtable is only read.RETURNINGshows its current values and never changes them. - Rows that triggers change on the target still show up in
RETURNINGas the final row version forAFTERtriggers' effects on that row. Later chapters cover this.
Summary
UPDATE ... FROMandDELETE ... USINGletRETURNINGread joined-table columns.- Use the table aliases in
RETURNINGand qualify every column. - One row comes back per changed target row, not per join match.
- With a one-to-many join, joined values in
RETURNINGare an arbitrary pick. INSERT ... SELECTcannot return columns from its source tables.
Exercise
Using the tables from this chapter, write one statement that sets priority to 10 on every work_items row whose project is not archived and whose status is 'open'. It must return the item id, the item title, the project name, and the new priority. Then explain why the output has exactly one row per updated item even if you also joined a table with several matching rows.
Show answer
UPDATE workitems AS w SET priority = 10 FROM projects AS p WHERE p.id = w.projectid AND NOT p.archived AND w.status = 'open' RETURNING w.id, w.title, p.name AS project_name, w.priority; Each target row is updated at most once, and RETURNING emits one row per updated target row. If a joined table had several matches for an item, PostgreSQL would use one of them, so the item would still appear once, and any column read from that joined table would come from an unspecified match.