AI Hints
Home›PostgreSQL Tutorial›Foreign Keys and RETURNING
PostgreSQL · Lesson 20 of 120

INSERT ... RETURNING

Get the new ID back.

⏱ 2 min read▶ Video at 16:52🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

After inserting a row, your app usually needs its new ID, to show a confirmation page. Returning gives back columns from the rows you just wrote, in the same step.

  • Insert
  • Need the new ID
  • RETURNING

Insert and return

Returning lists the columns to give back. Here, the new event ID and title. We insert two events at once. Run it. Both new rows come back, with their IDs.

query.sqlsql
INSERT INTO events (title, seats)
VALUES ('Mystery Book Club', 15),
       ('Cooking Demo', 25)
RETURNING event_id, title;
Output
 event_id |       title
----------+-------------------
        3 | Mystery Book Club
        4 | Cooking Demo
(2 rows)

INSERT 0 2
Also uses _setup.sql
CREATE TABLE events (
  event_id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  title    text NOT NULL,
  seats    integer NOT NULL CHECK (seats > 0));
INSERT INTO events (title, seats) VALUES ('Poetry Night', 30), ('Kids Story Hour', 20);

Why it matters

Without returning, you'd need a second query to find the new ID, which can go wrong when many users insert at once. Returning works on insert, update and delete. And it can return any expression.

keyvalue
No 2nd queryno race
Works onINSERT, UPDATE, DELETE
Returnsany columns
Postgresfeature since 8.2

Summary

Returning gives back the rows you just wrote, like their new IDs. Next, updating and deleting with returning.

Key takeaways
  • RETURNING
  • New IDs
  • One step
Next up: UPDATE and DELETE ... RETURNING — change and see