Sub topic 6
Getting the new ID back with RETURNING
This chapter assumes you can write basic CREATE TABLE, INSERT and SELECT statements. It also assumes you know what a primary key is and have a rough idea of how transactions commit and roll back. You should have seen how a GENERATED ... AS IDENTITY column fills in its own value. Here you learn how to get that value back to your application in the same round trip as the insert.
Why you need the generated ID
When the database generates an ID, your application does not know it until the row exists. Yet the application usually needs it right away. For example, after inserting an order you may want to insert its line items, return a URL such as /orders/42, or log the new key.
You could insert the row and then run a second query to find it. That is slow, and it is also unsafe, because the second query has to guess which row is yours. PostgreSQL avoids the problem with the RETURNING clause, which sends back columns of the rows that the statement just wrote.
The basic form
RETURNING goes at the end of an INSERT, UPDATE, DELETE or MERGE statement. It takes a list of expressions, just like a SELECT list. This chapter focuses on INSERT.
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer text NOT NULL
);
INSERT INTO orders (customer) VALUES ('Ada') RETURNING id;The statement returns a result set with one row and one column:
id
----
1
(1 row)The insert and the lookup happen in one statement and one network round trip. The ID you get back is the value stored in the row you just wrote. Other sessions inserting at the same time cannot change it.
What you can return
RETURNING is not limited to the key. You can return any column of the new row, * for every column, or any expression built from them. Values are those after column defaults and BEFORE triggers have run, so you see what was actually stored.
INSERT INTO orders (customer)
VALUES ('Grace')
RETURNING id, customer, upper(customer) AS shout, id * 10 AS scaled;You can also alias columns with AS, which helps when your driver maps result columns to field names.
INSERT INTO orders (customer) VALUES ('Linus') RETURNING *;Returning * is convenient for ad hoc work. In application code, name the columns you need. A later ALTER TABLE ... ADD COLUMN will otherwise change the shape of your result.
Multi-row inserts
If an INSERT writes several rows, RETURNING produces one result row per inserted row.
INSERT INTO orders (customer)
VALUES ('Margaret'), ('Dennis'), ('Barbara')
RETURNING id, customer;This is the main advantage over the older ways of reading the last ID. A statement that inserts a thousand rows can hand back all thousand keys at once.
Do not assume the rows come back in a documented order. In practice a plain VALUES list returns rows in the order you wrote them, but the SQL standard does not promise it. If you must match returned IDs to input rows, return a column that identifies each row, such as a natural key or an external reference, and match on that.
INSERT INTO orders (customer)
VALUES ('Margaret'), ('Dennis'), ('Barbara')
RETURNING id, customer;Because customer is returned alongside id, the application can pair each new ID with its input value without relying on row order.
Using the returned ID in the next statement
Often the new ID feeds a second insert. You can do this from the application, or entirely inside the database with a data-modifying common table expression (CTE). A CTE is a named subquery introduced with WITH. In PostgreSQL, a CTE can contain an INSERT ... RETURNING, and the main query can read its output.
CREATE TABLE order_items (
order_id bigint NOT NULL REFERENCES orders (id),
sku text NOT NULL,
qty integer NOT NULL
);
WITH new_order AS (
INSERT INTO orders (customer) VALUES ('Ada') RETURNING id
)
INSERT INTO order_items (order_id, sku, qty)
SELECT id, 'KEYBOARD', 2 FROM new_order;Both inserts run in a single statement, so they succeed or fail together. This pattern avoids a round trip and keeps the ID from ever leaving the database.
The following diagram shows the data flow.
Why not currval or lastval?
PostgreSQL also has sequence functions that report the last value handed out: currval('sequence_name') and lastval(). People coming from MySQL's LAST_INSERT_ID() or SQL Server's SCOPE_IDENTITY() often reach for them. They are session-local, so other sessions do not interfere with them. Even so, RETURNING is usually the better choice, for these reasons:
RETURNINGreports the value actually stored in the row. The sequence functions report only what the sequence last produced in your session.RETURNINGworks for multi-row inserts.lastval()gives you only the final value.lastval()reports the last sequence used by anynextvalcall in the session. A trigger that touches another sequence can make it return an unrelated number.currvalrequires you to know the sequence name, and it raises an error ifnextvalhas not been called in the session yet.- When an
INSERTsupplies an explicit ID (allowed withOVERRIDING SYSTEM VALUEorGENERATED BY DEFAULT), the sequence does not move.currvalthen does not match the row you inserted.RETURNINGstill does.
Returning values from other statements
RETURNING also works with UPDATE and DELETE. This chapter is about generated keys, but a short example shows how general the clause is.
UPDATE orders SET customer = 'Ada Lovelace'
WHERE id = 1
RETURNING id, customer;
DELETE FROM orders WHERE id = 1 RETURNING *;With UPDATE, RETURNING shows the new values of the row. With DELETE, it shows the row as it was before deletion. Starting in PostgreSQL 18, you can also use old and new aliases to see both versions in the same statement. Check your server version before relying on that.
INSERT ... ON CONFLICT and RETURNING
INSERT ... ON CONFLICT adds a gotcha. RETURNING reports only the rows the statement actually inserted or updated. With ON CONFLICT DO NOTHING, a conflicting row is skipped, so it does not appear in the output.
Suppose customers has a unique email column.
CREATE TABLE customers (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email text NOT NULL UNIQUE
);
INSERT INTO customers (email) VALUES ('[email protected]') RETURNING id;
INSERT INTO customers (email) VALUES ('[email protected]')
ON CONFLICT (email) DO NOTHING
RETURNING id;The second statement returns zero rows, because nothing was inserted. If your code expects an ID, it will find none. A common fix is DO UPDATE with a harmless assignment, which makes the existing row count as updated so that RETURNING includes it.
INSERT INTO customers (email) VALUES ('[email protected]')
ON CONFLICT (email) DO UPDATE SET email = EXCLUDED.email
RETURNING id;This returns the existing ID. The trade-off is that the conflicting row is rewritten, which creates a new row version and fires update triggers.
The skipped insert still consumes an identity value, because the sequence advances before the conflict check. The next successful insert will skip a number. A later chapter covers why gaps like this are normal.
Reading the result from application code
Every PostgreSQL driver treats a statement with RETURNING as a query that produces rows, so you read it like a SELECT. The details differ by driver, but the idea is the same. This Python example uses psycopg 3.
import psycopg
with psycopg.connect("dbname=shop") as conn:
row = conn.execute(
"INSERT INTO orders (customer) VALUES (%s) RETURNING id",
("Ada",),
).fetchone()
new_id = row[0]
print("created order", new_id)The connection context manager commits when the block ends without an error. Always pass values as parameters, as shown with %s, and never build the SQL by string concatenation.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Driver reports "no results to fetch" | The statement has no `RETURNING`, or `ON CONFLICT DO NOTHING` skipped the row | Add `RETURNING`, and handle the empty result |
| `cannot insert a non-DEFAULT value into column "id"` | You supplied an ID to a `GENERATED ALWAYS` column | Omit the column, or use `OVERRIDING SYSTEM VALUE` |
| `column "x" does not exist` in `RETURNING` | You named a column the table lacks | Check the column list and spelling |
| `currval ... is not yet defined in this session` | You called `currval` before any `nextval` | Use `RETURNING id` |
| Returned IDs do not match inputs | You relied on row order in a multi-row insert | Return a distinguishing column and match on it |
Key points
INSERT ... RETURNING idreturns the generated key in the same statement, with no second query.- It returns one row per inserted row and can return any column or expression.
- A data-modifying CTE lets one statement insert a parent row and its children.
- Prefer
RETURNINGovercurrvalandlastval, which depend on session state. - Skipped rows from
ON CONFLICT DO NOTHINGreturn nothing, and they still consume an identity value.
Exercise
You run INSERT INTO customers (email) VALUES ('[email protected]') ON CONFLICT (email) DO NOTHING RETURNING id; and the email already exists. What does the statement return, and how can you change it so the existing ID comes back?
Show answer
It returns zero rows, because no row was inserted and RETURNING reports only inserted or updated rows. Change DO NOTHING to DO UPDATE SET email = EXCLUDED.email so the existing row counts as updated and RETURNING includes its id. The cost is a rewritten row and any update triggers firing.
Exercise
Write one statement that inserts a customer into orders and then inserts one row into order_items for that new order, without sending the ID back to the client.
Show answer
WITH neworder AS (INSERT INTO orders (customer) VALUES ('Ada') RETURNING id) INSERT INTO orderitems (orderid, sku, qty) SELECT id, 'KEYBOARD', 2 FROM neworder;