Browse topics

INSERT with RETURNING

Version
19
Since
8.2
Review
Draft

Summary#

INSERT adds rows from a value list or a query. RETURNING gives back columns of the inserted rows, including generated keys and defaults, without a second query.

Syntax#

sql
INSERT INTO table_name (column_list)
VALUES (value_list), (value_list)
RETURNING column_list;

INSERT INTO table_name (column_list)
SELECT column_list FROM source_table
RETURNING column_list;

Example#

The output below is from PostgreSQL 19.0, produced with psql -X -q -A -P null=NULL -v ON_ERROR_STOP=1 -f example.sql in a scratch database. The script rolls back at the end, so it leaves nothing behind.

sql
BEGIN;

CREATE TEMPORARY TABLE tasks (
    task_id  integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    title    text NOT NULL,
    priority integer NOT NULL DEFAULT 3,
    state    text NOT NULL DEFAULT 'new'
);

-- RETURNING hands back generated and defaulted values.
INSERT INTO tasks (title)
VALUES ('Write report')
RETURNING task_id, title, priority, state;

-- A CTE lets the outer query order the returned rows.
WITH added AS (
    INSERT INTO tasks (title, priority)
    VALUES ('Fix build', 1), ('Review patch', DEFAULT)
    RETURNING task_id, title, priority
)
SELECT task_id, title, priority
FROM added
ORDER BY task_id;

-- INSERT can take its rows from a query.
WITH copied AS (
    INSERT INTO tasks (title, priority, state)
    SELECT title || ' (follow-up)', priority, 'queued'
    FROM tasks
    WHERE priority = 1
    RETURNING task_id, title, state
)
SELECT task_id, title, state
FROM copied
ORDER BY task_id;

ROLLBACK;

Expected output#

Text
task_id|title|priority|state
1|Write report|3|new
(1 row)
task_id|title|priority
2|Fix build|1
3|Review patch|3
(2 rows)
task_id|title|state
4|Fix build (follow-up)|queued
(1 row)

Common mistakes#

Reading max(task_id) after an insert can pick up a row from another session. Take the key from RETURNING. For a GENERATED ALWAYS identity column, omit the column or use DEFAULT to generate its value. Use OVERRIDING SYSTEM VALUE to store an explicit value, or OVERRIDING USER VALUE to ignore supplied identity values and generate new ones.

Version applicability#

PostgreSQL 8.2 added RETURNING. The identity column in the example requires PostgreSQL 10 or later, and using a data-changing statement inside WITH requires 9.1 or later.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0