Sub topic 2
Getting Generated Keys Back from INSERT
This chapter assumes you can write basic INSERT statements, know what a primary key and a column default are, and can run SQL in psql or another PostgreSQL client. The examples use the tasks table below. All of them work on any supported PostgreSQL version.
The problem: values you did not write
Some column values are produced by the database, not by your statement. An identity column assigns the next number, and DEFAULT now() fills in a timestamp. Your application usually needs those values right after the insert, for example to show the new record's id or to use it as a foreign key.
The older approach is a second round trip: insert, then run SELECT ... WHERE title = ..., or call lastval(). Both have drawbacks. The extra SELECT costs another query and can race with concurrent writers. lastval() depends on session state and returns the wrong value if a trigger or another statement touched a sequence in between.
INSERT ... RETURNING avoids both. It returns the values of the rows that this statement stored, as an ordinary result set, in the same round trip.
The basic form
Create the table that the rest of the chapter uses:
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 statement never mentions id or status. PostgreSQL fills both in, and RETURNING reports what it stored. In psql the output looks like this:
id | title | status
----+--------------+--------
1 | Write report | open
2 | Review PR | open
(2 rows)
INSERT 0 2The command tag INSERT 0 2 still appears after the rows. The result set is in addition to it, not a replacement.
The statement also returned two rows from one INSERT. RETURNING produces one output row for every row inserted, however many that is.
What RETURNING can contain
The RETURNING list takes the same kinds of items as a SELECT list: column names, expressions, aliases and *. A later chapter covers these in detail. For now, two forms matter.
RETURNING idreturns only the key.RETURNING *returns every column of the inserted row, including all generated ones.
To read a column in the list you need SELECT privilege on it, in addition to INSERT privilege on the table. A role that can insert but not select gets a permission error if it uses RETURNING.
Identity columns and serial
Three column definitions are common for generated keys. They differ in what happens when a statement supplies its own value.
| Definition | Explicit value in INSERT | Notes |
|---|---|---|
| `GENERATED ALWAYS AS IDENTITY` | Error, unless you add `OVERRIDING SYSTEM VALUE` | Standard SQL. Protects the column from accidental values. |
| `GENERATED BY DEFAULT AS IDENTITY` | Accepted | Standard SQL. The generator is used only when you omit the column. |
| `serial` / `bigserial` | Accepted | PostgreSQL shorthand that creates a sequence and a default. Prefer identity in new tables. |
With GENERATED ALWAYS, this fails:
INSERT INTO tasks (id, title)
VALUES (100, 'Imported task')
RETURNING id;PostgreSQL reports cannot insert a non-DEFAULT value into column "id". If you are loading data that already has ids, state your intent explicitly:
INSERT INTO tasks (id, title)
OVERRIDING SYSTEM VALUE
VALUES (100, 'Imported task')
RETURNING id;RETURNING then reports 100. Note that the identity sequence does not move forward when you supply a value. If the sequence later reaches 100, an insert collides with the imported row and fails on the primary key. After a bulk import, reset the sequence with setval.
Matching returned rows to your input
A multi-row insert returns several rows, and you often need to know which output row belongs to which input row. In practice PostgreSQL returns rows for a plain VALUES list in the order you wrote them. The documentation does not promise this, and it is even less dependable for INSERT ... SELECT, where the query plan can reorder rows.
Because title is UNIQUE in this table, it works as a natural key for matching:
INSERT INTO tasks (title)
VALUES ('Plan sprint'), ('Update docs')
RETURNING id, title;The client builds a map from title to id and never depends on row order. If your input has no natural key, you can include a client-side sequence number in a VALUES list and join through a CTE, which a later chapter covers.
Inserts that have no column list
INSERT ... DEFAULT VALUES inserts one row made entirely of defaults. It suits tables where every column is generated:
CREATE TABLE audit_events (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
created_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO audit_events DEFAULT VALUES
RETURNING id, created_at;You can also combine RETURNING with INSERT ... SELECT, which copies rows from a query and returns each new row:
INSERT INTO tasks (title, status)
SELECT title || ' (copy)', status
FROM tasks
WHERE status = 'open'
RETURNING id, title;The tasks_archive-style copy patterns you will meet later all rest on this form.
What RETURNING shows when triggers exist
RETURNING reports the row as it was stored by this statement. That includes the effect of BEFORE INSERT triggers, because they modify the row before it is written. It does not include later changes made by AFTER triggers to the same row, because those run after the row is stored and after the returned values are computed.
This trigger trims whitespace before the row is written:
CREATE FUNCTION tasks_normalize() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
NEW.title := btrim(NEW.title);
RETURN NEW;
END;
$$;
CREATE TRIGGER tasks_normalize_trg
BEFORE INSERT ON tasks
FOR EACH ROW EXECUTE FUNCTION tasks_normalize();
INSERT INTO tasks (title)
VALUES (' Triage bugs ')
RETURNING id, title;The returned title is Triage bugs, without the spaces. The value the client sent is not what comes back. If your application compares the returned value with what it sent, expect differences when a trigger or a default rewrites data. A BEFORE trigger that returns NULL skips the row, so that row does not appear in the output.
Failures, rollbacks and gaps
RETURNING only reports rows that were actually inserted. If any row violates a constraint, the whole statement fails with an error and returns no rows. The values you saw in a successful result are still subject to the surrounding transaction: if you roll back afterwards, those rows no longer exist.
Identity and serial values come from a sequence, and sequences are not transactional. A failed or rolled-back insert still consumes a value:
INSERT INTO tasks (title) VALUES ('Review PR');If Review PR already exists, this fails on the unique constraint. The identity value was already drawn, so the next successful insert skips a number. With the earlier rows, the next new task could get id 4 instead of 3.
Common mistakes
- Reading
lastval()orcurrval()instead. These depend on session state and can return a value from a different insert. UseRETURNING. - Expecting a result with
ON CONFLICT DO NOTHING. A skipped row produces no output row, so the result can be empty or shorter than the input. A later chapter covers this. - Sending an explicit id to a
GENERATED ALWAYScolumn. Omit the column, or addOVERRIDING SYSTEM VALUEdeliberately. - Ignoring zero-row results in client code. Always handle the case where fewer rows come back than you sent.
- Assuming returned values equal sent values. Triggers, defaults and type coercion can change them.
Exercises
Exercise
Write a statement that creates a table notes with a bigint identity primary key id, a body text NOT NULL, and a created_at timestamptz that defaults to the current time. Then insert two notes in one statement and return each note's id, body and created_at.
Show answer
CREATE TABLE notes ( id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, body text NOT NULL, createdat timestamptz NOT NULL DEFAULT now() ); INSERT INTO notes (body) VALUES ('First note'), ('Second note') RETURNING id, body, createdat; Both rows share the same created_at, because now() returns the transaction start time.
Exercise
A client inserts three rows into tasks in one statement and zips the returned ids with its input list by position. Why is this risky, and what is a safer approach?
Show answer
PostgreSQL does not guarantee that RETURNING rows come back in input order, especially for INSERT ... SELECT. The ids could be attached to the wrong inputs. Instead, include a column that identifies each input row, such as the unique title, in the RETURNING list and match on that value.
Exercise
Your insert of 'Review PR' fails on the unique constraint on title. The next successful insert gets an id two higher than the previous successful one. Is something wrong with the database?
Show answer
No. The identity value was drawn from the sequence before the constraint check failed, and sequences do not roll back. Gaps in identity values are expected.