Sub topic 5
Expressions, Aliases and * in the RETURNING List
This chapter assumes you can write basic INSERT, UPDATE and DELETE statements, know what a primary key and a column default are, and can run SQL in psql or another PostgreSQL client. You also need the idea from earlier chapters that RETURNING sends back the rows a statement changed. Here we look at what you can put in the RETURNING list and how PostgreSQL names the output columns.
The RETURNING list works like a SELECT list
The RETURNING list follows the same rules as the output list of a SELECT. Each item can be a column, an expression, a function call, *, or table.*. Each item can also have an alias. The expressions are evaluated once for every row the statement changes, and they see the row as it is after the change.
The examples below use one table. Run this setup first. If you still have a tasks table from an earlier chapter, the DROP statement removes it so the identity values start at 1.
DROP TABLE IF EXISTS tasks;
CREATE TABLE tasks (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title text NOT NULL UNIQUE,
status text NOT NULL DEFAULT 'open',
updated_at timestamptz NOT NULL DEFAULT now()
);Expressions and aliases
Any expression that uses the target table's columns is allowed. The next statement returns a transformed title, a boolean test, and a cast.
INSERT INTO tasks (title)
VALUES ('Plan sprint'), ('Fix bug')
RETURNING
id,
upper(title) AS shout_title,
status = 'open' AS is_open,
updated_at::date AS day;The result has four columns named id, shout_title, is_open and day. Both rows have is_open set to true, because the default status is 'open'.
You can use the same kind of expressions in UPDATE. This one builds a label with string concatenation and a CASE expression.
UPDATE tasks
SET status = 'done', updated_at = now()
WHERE title = 'Fix bug'
RETURNING
id,
title || ' [' || status || ']' AS label,
CASE WHEN status = 'done' THEN 'finished' ELSE 'pending' END AS state;The status in the expression is the new value, 'done'. The returned row has the label Fix bug [done] and the state finished.
How output columns are named
If you do not give an item an alias, PostgreSQL picks a name for it. The rules are the same as for SELECT.
| RETURNING item | Output column name | Column | Column |
|---|---|---|---|
| `id` | `id` | ||
| `t.title` | `title` | ||
| `upper(title)` | `upper` | ||
| `CASE WHEN ... END` | `case` | ||
| `id * 10` | `?column?` | ||
| `status = 'done'` | `?column?` | ||
| `title \ | \ | '!'` | `?column?` |
A plain column keeps its name, and a function call takes the function's name. Operator expressions end up as ?column?. Client libraries that read results by column name cannot tell two ?column? columns apart, so give every computed item an alias.
Some points about aliases:
ASis optional for column aliases, but writing it avoids mistakes. A missing comma between two items can turn the second item into an accidental alias for the first.- Unquoted aliases are folded to lowercase.
AS isOpenreturns a column namedisopen. Use double quotes, as inAS "isOpen", to keep the case. Quotes are also needed for aliases that contain spaces. - Duplicate output names are allowed.
RETURNING id, idreturns two columns that are both namedid. psql shows both, but a client that stores rows in a dictionary keeps only one.
Using * and table.*
RETURNING * returns every column of the target table, in table-definition order. You can mix it with other items, and the extra items come after the table's columns.
UPDATE tasks
SET updated_at = now()
WHERE title = 'Plan sprint'
RETURNING *, length(title) AS title_length;The output has id, title, status, updated_at and then title_length.
You can give the target table an alias with AS. After that you must use the alias, not the original table name, when you qualify columns.
UPDATE tasks AS t
SET status = 'blocked'
WHERE t.title = 'Plan sprint'
RETURNING t.*, t.status <> 'open' AS needs_attention;t.* expands to the target table's columns. This form matters more when the statement involves other tables, because plain * can also include columns from those tables. Later chapters cover UPDATE ... FROM and DELETE ... USING, where this distinction is important.
Subqueries see the old snapshot
A scalar subquery is allowed in a RETURNING item. It reads the database as it was when the statement started, so it does not see the rows that the same statement is changing.
INSERT INTO tasks (title)
VALUES ('Write docs')
RETURNING id, title, (SELECT count(*) FROM tasks) AS rows_seen;If you ran the earlier examples in order, rows_seen is 2, not 3. The new row is in the output, but the subquery's snapshot was taken before the insert. The same rule applies to UPDATE and DELETE. A subquery in RETURNING shows the state before the statement ran, while a plain column reference shows the row after the change.
What is not allowed
Aggregate functions and window functions cannot appear in a RETURNING list. The reason is that RETURNING produces one output row per changed row, and it does not group or reorder them. This statement fails:
UPDATE tasks
SET updated_at = now()
RETURNING count(*);PostgreSQL reports an error saying that aggregate functions are not allowed in RETURNING. To aggregate the changed rows, return them from a data-modifying CTE and aggregate in the outer query.
WITH changed AS (
UPDATE tasks
SET updated_at = now()
WHERE status = 'open'
RETURNING id
)
SELECT count(*) AS rows_touched
FROM changed;The same trick gives you ORDER BY. A RETURNING clause has no ORDER BY of its own. The order of returned rows for UPDATE and DELETE follows the order in which PostgreSQL happens to process them, and you should not rely on it. If the order matters, select from the CTE and sort there.
WITH changed AS (
UPDATE tasks
SET updated_at = now()
RETURNING id, title
)
SELECT id, title
FROM changed
ORDER BY title;Volatile functions and timestamps
A volatile function in the RETURNING list is called once per row. For example, random() gives each returned row a different value, and nothing ties that value to anything stored in the table.
Timestamps need care. now() returns the start time of the current transaction, so it is the same for every row and the same as the value stored by DEFAULT now() in that transaction. clock_timestamp() returns the actual time at the moment it is called, so it usually differs from the stored updated_at. If you want to show the value that was stored, return the column itself: RETURNING updated_at.
Common mistakes
- Naming a column that does not exist in the target table. RETURNING can only use columns of the target table (and of other tables joined in with
FROMorUSING). It cannot refer to a column of theVALUESlist or to an alias defined in the same RETURNING list. - Reusing an alias in the same list.
RETURNING id * 2 AS double_id, double_id + 1fails, because aliases are not visible to other items in the same list. - Using the original table name after giving the table an alias. After
UPDATE tasks AS t, writingtasks.idis an error. - Expecting RETURNING to show the old value. For UPDATE it shows the new value. Seeing both needs a different technique, covered in a later chapter.
- Reading
?column?results by name in client code. Add aliases.
Exercise
You run DELETE FROM tasks WHERE status = 'blocked' RETURNING id, upper(title), id * 10;. What are the names of the three output columns, and what change would make a Python dictionary row hold all three values reliably?
Show answer
The names are id, upper and ?column?. The first is the plain column, the second takes the function's name, and the third is an operator expression with no inferred name. Adding aliases to the computed items, for example upper(title) AS title_upper, id * 10 AS id_x10, gives every column a unique, meaningful name.
Exercise
Write one statement that sets the status of the task titled 'Write docs' to 'done' and returns the task's id, a boolean column named is_finished that is true when the new status is 'done', and all the table's columns after those two. Which alias rule would break if you wrote AS isFinished and then looked for isFinished in your client?
Show answer
UPDATE tasks SET status = 'done' WHERE title = 'Write docs' RETURNING id, status = 'done' AS is_finished, *; The unquoted alias isFinished is folded to lowercase, so the column comes back as isfinished. To keep the mixed case you would write AS "isFinished".