Sub topic 2
Getting generated keys back from INSERT
This chapter assumes you know basic INSERT syntax, primary keys, column defaults, and how to run SQL in psql or another PostgreSQL client.
When PostgreSQL creates values during an INSERT, add a RETURNING clause to receive those values immediately. This avoids a second SELECT and prevents mistakes such as retrieving the wrong row after concurrent inserts.
The basic pattern
Place RETURNING after the VALUES, SELECT, or ON CONFLICT part of the statement:
INSERT INTO table_name (column_a, column_b)
VALUES (value_a, value_b)
RETURNING generated_column, column_a, column_b;The statement produces a result set. Each returned row represents one row inserted by that statement.
A primary key defined with GENERATED ALWAYS AS IDENTITY is a common example:
CREATE TABLE tasks (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title text NOT NULL UNIQUE,
status text NOT NULL DEFAULT 'open',
created_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO tasks (title)
VALUES ('Write report'), ('Review pull request')
RETURNING id, title, status, created_at;The application receives both generated IDs, the default status, and the generated timestamp in one response.
| Inserted column | How PostgreSQL supplies its value |
|---|---|
| `id` | Identity sequence |
| `title` | The value in `VALUES` |
| `status` | Column default, because it was omitted |
| `created_at` | `now()` column default |
Why this is safer than a follow-up query
A common but unsafe pattern is:
- Insert a row.
- Query the table for the newest row.
- Assume that row belongs to the current request.
Another transaction might insert a row between those operations. RETURNING binds the generated values to the exact rows changed by the original statement.
The returned identity value is also safer than trying to calculate a sequence value yourself. PostgreSQL assigns the identity value as part of the insert, then reports the assigned value.
Returning expressions and all columns
A RETURNING list follows the same general expression rules as a SELECT list. You can rename a returned value, calculate a value, or return every column with *.
INSERT INTO tasks (title)
VALUES ('Publish guide')
RETURNING
id AS task_id,
upper(title) AS normalized_title,
status,
created_at;Returning * is convenient when the client needs the complete inserted row:
INSERT INTO tasks (title)
VALUES ('Archive notes')
RETURNING *;Prefer an explicit column list in stable application interfaces. It documents the data being returned and avoids changing the client response unexpectedly when a table gains another column.
Multiple rows and result handling
With a multi-row insert, RETURNING can produce multiple rows:
INSERT INTO tasks (title)
VALUES ('Plan demo'), ('Test deployment'), ('Update changelog')
RETURNING id, title;Do not assume that returned rows are ordered the same way as the input values unless your application has a reliable way to associate them. SQL does not generally promise result ordering without ORDER BY, and RETURNING does not provide an ORDER BY clause for the affected rows.
A client library usually exposes these returned rows through the same result-reading API used for a SELECT. Read the result set and obtain the generated key from the returned id column. If the insert affects no rows because its WHERE condition or conflict action prevents insertion, there may be no returned row.
Exercise
Why is INSERT ... RETURNING id safer than inserting a row and then selecting the newest ID from the table?
Show answer
RETURNING reports the identity assigned to the exact row inserted by that statement, so another transaction cannot cause the follow-up query to select the wrong row.