Sub topic 1
Returning Changed Rows with RETURNING in PostgreSQL
Prerequisites
You should know basic SQL statements (SELECT, INSERT, UPDATE, DELETE), how primary keys and column defaults work, and how to run queries in psql or another PostgreSQL client. The examples run on any supported PostgreSQL version.
What RETURNING does
RETURNING is an optional clause at the end of an INSERT, UPDATE, DELETE, or MERGE statement. It lists the columns or expressions to send back for each row the statement changed. The values come back in the same round trip as the write.
A common alternative is to write a row and then run a SELECT to read it back. That second query costs another round trip. Another session can also change the row between the two statements, so the SELECT may not show what your write produced. RETURNING avoids both problems because the values come from the same statement that made the change.
Getting generated keys from INSERT
Create a table and insert two rows:
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()
);
INSERT INTO tasks (title)
VALUES ('Write report'), ('Review PR')
RETURNING id, title, status;The result includes the identity values PostgreSQL generated and the default status. You supplied neither value, yet your code receives both without a second query.
-- Run the CREATE TABLE once. Running the INSERT again fails
-- with a unique violation on title.Seeing new row values after UPDATE
UPDATE ... RETURNING shows each row as it looks after the update:
UPDATE tasks
SET status = 'done', updated_at = now()
WHERE title = 'Write report'
RETURNING id, status, updated_at;If the WHERE clause matches no rows, the statement returns zero rows and reports no error. Check for an empty result in your application before assuming the update happened.
Exercise
Your application inserts a task and needs its id. Using RETURNING, what single statement do you run, and why is it safer than INSERT followed by SELECT?
Show answer
Run INSERT INTO tasks (title) VALUES ('Plan sprint') RETURNING id; The id comes from the same statement that created the row, so no other session can change or confuse it between two statements, and the app saves one round trip.