Sub topic 6
Reading `RETURNING` Results from Application Code
This chapter assumes you know basic SELECT, INSERT, UPDATE, and DELETE, understand primary keys and defaults, and can connect to PostgreSQL with psql or another client.
A PostgreSQL statement with RETURNING produces a result set. Application code reads that result set just as it reads rows from SELECT. The difference is that the rows come from the operation that changed the data.
Fetching returned rows
The following example uses Psycopg 3, a PostgreSQL driver for Python. Install it with pip install "psycopg[binary]". Set DATABASE_URL to a connection string before running the program.
import os
import psycopg
database_url = os.environ["DATABASE_URL"]
with psycopg.connect(database_url) as connection:
with connection.cursor() as cursor:
cursor.execute(
"""
UPDATE tasks
SET status = %s, updated_at = now()
WHERE id = %s
RETURNING id, title, status, updated_at
""",
("done", 42),
)
row = cursor.fetchone()
if row is None:
print("No task with that id was updated")
else:
task_id, title, status, updated_at = row
print(task_id, title, status, updated_at)execute() sends the statement and its parameters. fetchone() reads one returned row. If no row matches the WHERE clause, fetchone() returns None.
For operations that can affect several rows, use fetchall() or iterate over the cursor:
with psycopg.connect(database_url) as connection:
with connection.cursor() as cursor:
cursor.execute(
"""
DELETE FROM tasks
WHERE status = %s
RETURNING id, title
""",
("done",),
)
deleted_tasks = cursor.fetchall()
for task_id, title in deleted_tasks:
print(f"Deleted {task_id}: {title}")An INSERT can return generated identity values and defaults immediately:
with psycopg.connect(database_url) as connection:
with connection.cursor() as cursor:
cursor.execute(
"""
INSERT INTO tasks (title)
VALUES (%s)
RETURNING id, title, status, updated_at
""",
("Write report",),
)
task_id, title, status, updated_at = cursor.fetchone()
print(f"Created task {task_id} with status {status}")The connection context commits when the block exits successfully. If an exception escapes the block, Psycopg rolls the transaction back. Read the returned rows before leaving the transaction if later code depends on them.
Choose a stable result shape
List the columns the application needs instead of using RETURNING *. Selecting explicit columns documents the interface and avoids accidentally changing the result when the table gains a column.
Column aliases work in RETURNING, so you can choose names that match application conventions:
UPDATE tasks
SET status = 'done'
WHERE id = 42
RETURNING id AS task_id, status AS current_status;With Psycopg, returned columns are tuples by default. A dictionary row factory can make code clearer when many columns are returned:
import psycopg
from psycopg.rows import dict_row
with psycopg.connect(database_url, row_factory=dict_row) as connection:
with connection.cursor() as cursor:
cursor.execute(
"""
INSERT INTO tasks (title)
VALUES (%s)
RETURNING id, title, status
""",
("Review PR",),
)
task = cursor.fetchone()
print(task["id"], task["status"])Transactions and application decisions
RETURNING does not commit a transaction. It only returns the rows changed by the statement. The application still decides whether to commit or roll back.
A returned row also does not mean that every requested input produced a row. UPDATE and DELETE return one row per affected row. ON CONFLICT DO NOTHING returns no row for a conflicting input, so application code must handle an empty result.
Exercise
An application runs UPDATE tasks SET status = 'done' WHERE id = %s RETURNING id, status. What should it do when fetchone() returns None?
Show answer
Treat it as no matching task, or as a not-found result. The statement changed zero rows, so there is no returned task to process.