Sub topic 6
Reading RETURNING results from application code
This chapter assumes you can run INSERT, UPDATE and DELETE in psql, and that you have written basic application code that talks to PostgreSQL. It also assumes you have the tasks table from earlier chapters. The examples use Python with psycopg 3 and Node.js with pg. The same ideas apply to any driver.
A RETURNING statement is a query
A statement with a RETURNING clause produces a result set, just like a SELECT. The client receives a row description, then one data row for each affected row, then a command tag such as INSERT 0 1. The command tag reports the number of affected rows.
Many drivers have separate calls for statements that return rows and statements that only report a count. With RETURNING, use the call that reads rows.
Because the result is a normal result set, three things follow:
- You must read it with a fetch call, or an equivalent such as
rowsin Node. - It can contain zero, one or many rows. Your code has to handle all three.
- Column values arrive with the types the driver maps for each PostgreSQL type, not as text.
Reading one row from an INSERT
When you insert one row, you usually want one row back. This Python example inserts a task and reads its generated key and default status.
import os
import psycopg
from psycopg.rows import dict_row
with psycopg.connect(os.environ["DATABASE_URL"], row_factory=dict_row) as conn:
cur = conn.execute(
"INSERT INTO tasks (title) VALUES (%s) RETURNING id, title, status",
("Write report",),
)
task = cur.fetchone()
print(task)
# {'id': 1, 'title': 'Write report', 'status': 'open'}Run this once. The title column is UNIQUE, so a second run raises a unique violation.
The values are passed as parameters (%s with a tuple), not pasted into the SQL string. RETURNING does not change how you should build queries. The with block commits when it exits without an exception and rolls back when it exits with one.
row_factory=dict_row returns each row as a dictionary. Without it, rows are tuples, and you read columns by position. Dictionaries are safer here because the RETURNING list is easy to reorder by accident.
Handling zero rows from UPDATE
UPDATE ... RETURNING returns nothing when the WHERE clause matches no row. This is not an error. The statement succeeds with zero rows. In psycopg, fetchone() returns None in that case. Check for it.
def complete_task(conn, title):
cur = conn.execute(
"""
UPDATE tasks
SET status = 'done', updated_at = now()
WHERE title = %s
RETURNING id, status, updated_at
""",
(title,),
)
row = cur.fetchone()
if row is None:
raise LookupError(f"no task titled {title!r}")
return rowThis replaces the pattern "UPDATE, then SELECT to check it worked". An empty result tells you that nothing matched. You can also read cur.rowcount, which psycopg fills from the command tag.
Reading many rows from DELETE
A DELETE or UPDATE can affect any number of rows. Use fetchall() to read them as a list.
def purge_done(conn):
cur = conn.execute(
"DELETE FROM tasks WHERE status = %s RETURNING id, title",
("done",),
)
deleted = cur.fetchall()
for task in deleted:
print("removed", task["id"], task["title"])
return deletedfetchall() loads every row into memory. A DELETE that removes millions of rows will also return millions of rows to your process. If you only need the count, drop RETURNING and read rowcount. If you need the rows but there are too many, delete in batches or read them from a server-side cursor.
The same pattern in Node.js
The pg library has one query method for every statement. It returns an object with rows (an array) and rowCount. A RETURNING clause fills rows.
import pg from "pg";
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
const result = await pool.query(
"UPDATE tasks SET status = $1, updated_at = now() WHERE title = $2 RETURNING id, status, updated_at",
["done", "Review PR"],
);
if (result.rowCount === 0) {
console.log("no matching task");
} else {
const [task] = result.rows;
console.log(task.id, task.status, task.updated_at);
}
await pool.end();Save this as an ES module, for example update.mjs, so that top-level await works.
Watch the type mapping. By default, pg returns bigint columns, including a bigint identity key, as JavaScript strings. This avoids losing precision above 2^53. numeric columns are also strings. timestamptz columns become Date objects. If you compare task.id to a number with ===, the comparison fails.
What other drivers and ORMs do
| Tool | How to read RETURNING output |
|---|---|
| `psycopg` (Python) | `fetchone()`, `fetchall()` on the cursor after `execute` |
| `pg` (Node.js) | `result.rows` and `result.rowCount` |
| `pgx` (Go) | `QueryRow(...).Scan(...)` for one row, `Query` for many |
| JDBC | `executeQuery()` on a `PreparedStatement`, or `RETURN_GENERATED_KEYS` with `getGeneratedKeys()` |
| SQLAlchemy | `insert(...).returning(...)`, then `.scalar_one()` or `.all()` |
| Django ORM | Fills the primary key on `save()` and `create()` for you |
JDBC deserves a note. RETURN_GENERATED_KEYS makes the PostgreSQL driver append a RETURNING clause for you. Calling executeQuery() with your own RETURNING list gives you control over exactly which columns come back.
Rows are not matched to your input by position
When you insert several rows in one statement, you get several rows back. In practice, INSERT ... VALUES returns them in the order you listed them. The PostgreSQL documentation does not promise this, and it does not hold for INSERT ... SELECT or for updates and deletes.
If you need to match returned rows to your input, include a column that identifies each row. A unique natural key works well.
titles = ["Write report", "Review PR", "Plan sprint"]
cur = conn.execute(
"""
INSERT INTO tasks (title)
SELECT unnest(%s::text[])
RETURNING id, title
""",
(titles,),
)
ids_by_title = {row["title"]: row["id"] for row in cur.fetchall()}This sends the whole list as one array parameter. The dictionary ids_by_title lets you find each key without relying on row order.
Batches: executemany needs care
Calling execute once per row costs one network round trip per row. Drivers offer batch helpers, but not all of them keep the RETURNING rows.
- In
psycopg3,executemany(..., returning=True)keeps the result of each statement. You then walk through them withnextset(). - In the older
psycopg2,executemanydiscardsRETURNINGrows. Use a single multi-rowINSERTor theexecute_valueshelper withfetch=True.
If your driver's batch helper is unclear about this, use one multi-row statement as in the previous section. It makes one round trip and returns all rows.
Transactions and lost responses
The rows you read are the state inside your current transaction. They are not committed until the transaction commits.
- If the transaction rolls back, the data you read from
RETURNINGnever existed for other sessions. Identity values and sequence numbers it consumed are not given back, so your keys can have gaps. - Do not hand a returned
idto another service, queue or user before the commit succeeds. The receiver may look the row up and not find it. - If the connection drops after you sent the statement but before you read the response, you do not know whether it committed. The returned row is lost. A retry of a plain
INSERTcan then create a duplicate. A unique key on a natural identifier, plusON CONFLICT, makes retries safe. The next chapters cover this.
Common mistakes in client code
- Using an execute-only call. Some APIs return only a count for
UPDATEandDELETE, and drop the rows. Use the query call that returns a result set. - Calling fetch on a statement without RETURNING.
psycopgraises an error because the last operation produced no result set. Keep the fetch next to theRETURNINGclause it belongs to. - Assuming exactly one row. Unpacking
rows[0]fails with an index error when nothing matched. CheckrowCountor test forNone. - Ignoring type mapping. Compare
bigintkeys from Node as strings, or set a type parser if you want numbers. - Fetching from the wrong cursor. With a shared cursor, a later
executereplaces the earlier result. Read the rows before you run the next statement.
Exercise
Your Node.js service runs UPDATE tasks SET status = 'done' WHERE id = $1 RETURNING id, status with pool.query. The code does const task = result.rows[0]; return task.status; and sometimes crashes with "Cannot read properties of undefined". What causes this, and how do you fix it? Also, why might task.id === 7 be false even when the row with id 7 was updated?
Show answer
The crash happens when no row has the given id. The UPDATE succeeds with zero rows, so result.rows is an empty array and rows[0] is undefined. Fix it by checking result.rowCount === 0 (or result.rows.length === 0) before reading the row, and return a "not found" result or throw a clear error. The comparison fails because pg returns bigint columns as strings by default, so task.id is "7", not 7. Compare against a string, convert with Number or BigInt, or register a type parser for bigint.
Exercise
You insert three tasks with one multi-row INSERT ... RETURNING id, title and need to attach each new id to the matching input item. Why should you not rely on the order of the returned rows, and what do you do instead?
Show answer
The documentation does not guarantee that returned rows follow the order of your input, and the order is less predictable for INSERT ... SELECT, UPDATE and DELETE. Include a column that identifies each row in the RETURNING list, such as the unique title, and build a lookup (for example a dictionary from title to id) from the returned rows.