INSERT RETURNING: retrieve newly inserted values
Overview
RETURNING returns selected values from the rows modified by an INSERT in engines that support it. It is useful for retrieving generated IDs and defaults without guessing which row was inserted. Both PostgreSQL 17 and SQLite 3.46.1 support this form. Load the V51 fixture and run each example independently; the returned rows are observed before ROLLBACK.
First example
BEGIN;INSERT INTO ins_item(sku,price_cents) VALUES ('C4',99)RETURNING id,sku,quantity,note;ROLLBACK;Observed SQLite result (rows in JSON):
[ [ 3, "C4", 0, "pending" ]]How it works
Choose only the returned columns the application needs. One successful inserted row yields one result row here. RETURNING is not a commit: the transaction may later roll back or fail at commit. For multi-row INSERT, do not depend on the result order; correlate using a returned business key. SQLite RETURNING cannot be used as a subquery or DML CTE result and does not reflect subsequent AFTER-trigger modifications. PostgreSQL supports data-modifying CTEs with RETURNING; SQL Server uses the different OUTPUT syntax. These are dialect-specific, not interchangeable statements.
Practical example
BEGIN;INSERT INTO ins_job DEFAULT VALUESRETURNING id,state;ROLLBACK;Observed SQLite result (rows in JSON):
[ [ 1, "queued" ]]Practice and mistakes
Practice: insert a new product C4 with price 99 and return sku, id, note. Predict the default and rollback. Then try inserting an existing SKU in a separate transaction: no successfully inserted row can be returned from the failed ordinary INSERT. Mistake: treating returned IDs as durable before COMMIT or matching multiple returned rows by position.