Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Performance & internals
Stage 5: Specialization

Part 11 / Topic 4 of 7

RETURNING: every write its own receipt

You have been using it all part — now name the rule: any INSERT, UPDATE or DELETE can return the rows it touched, taking anything a SELECT list takes:

INSERT INTO customers (first_name, last_name, email, city, signup_date)
VALUES ('Kiran', 'Rao', '[email protected]', 'Mumbai', '2025-05-01')
RETURNING customer_id, lower(email) AS email;
 customer_id |       email       
-------------+-------------------
           7 | [email protected]
(1 row)

INSERT 0 1

That generated customer_id back in one round trip is the headline use — applications need the id of what they just created, and RETURNING beats a follow-up SELECT (which, under concurrency, might not even find the same row). For UPDATEs and DELETEs it's the audit trail: what exactly did I just change? Postgres answers as part of the write itself.

🧪 Quick quiz — answer from memory, then check.

  1. Why is RETURNING better than SELECT-after-INSERT for the new id?
  2. Which statements accept RETURNING?
Show the answers
  1. One atomic round trip, and it reports the actual row this statement wrote — no race with concurrent changes.
  2. INSERT, UPDATE and DELETE (and MERGE, below).

Exercise 4: The rollback drill

What to do: Inside a transaction: delete all payments, count to prove they're gone, roll back, count to prove they're back. From memory.

Sample output:

 inside_transaction 
--------------------
                  0
(1 row)

 after_rollback 
----------------
              7
(1 row)

💡 Hint: BEGIN, do the damage, inspect it, ROLLBACK. This drill is the habit.


Show the solution to Exercise 4
-- Exercise 4: The rollback drill
BEGIN;
DELETE FROM payments;
SELECT count(*) AS inside_transaction FROM payments;
ROLLBACK;
SELECT count(*) AS after_rollback FROM payments;

Search the guide