Inserting, Updating and Deleting · Lesson 39 of 64

SQL RETURNING

What you will learn

  • How RETURNING gives back rows from an INSERT, UPDATE or DELETE
  • How to get the new id of an inserted row
  • How to see the old rows of a delete
  • Why it is better than a second query

This lesson runs on the sample database you chose in lesson 1.1 (use the Example data picker at the top). The changes happen only in your browser's copy of the data; Reset data puts everything back. Run the cells from top to bottom.

1. The problem

After an INSERT you often need the id the database gave the new row, for example to add rows to a child table. After an UPDATE you may want to see the new values, and after a DELETE, which rows were removed. The old way is a second SELECT, which costs a round trip and can race with other changes. RETURNING hands the rows back in the same statement.

2. INSERT ... RETURNING

Add RETURNING column, ... at the end. The statement now returns a result table with one row per inserted row:

INSERT INTO customers (first_name, last_name, email, city, country, joined_on)
VALUES ('Sana', 'Karim', 'sana.karim@example.com', 'Cairo', 'Egypt', '2026-10-06')
RETURNING customer_id, first_name, joined_on, is_active;
customer_id  first_name  joined_on   is_active
-----------  ----------  ----------  ---------
        421  Sana        2026-10-06          1
(1 row)
INSERT INTO branches (name, city) VALUES ('Midtown', 'Austin'), ('Uptown', 'Austin')
RETURNING branch_id, name, city;
branch_id  name     city
---------  -------  ------
        7  Midtown  Austin
        8  Uptown   Austin
(2 rows)
INSERT INTO students (first_name, last_name, birth_date, enrolled_year, email)
VALUES ('Sana', 'Karim', '2014-01-30', 2026, 'sana.karim@student.example')
RETURNING student_id, first_name, enrolled_year, guardian_name;
student_id  first_name  enrolled_year  guardian_name
----------  ----------  -------------  -------------
       361  Sana                 2026  NULL
(1 row)

The new id came back, along with the defaults the database filled in (for example is_active). Your program can use the id at once.

3. UPDATE ... RETURNING

The returned columns show the values after the update:

UPDATE products SET price = ROUND(price * 1.1, 2) WHERE product_id IN (1, 2)
RETURNING product_id, name, price;
product_id  name         price
----------  -----------  -----
         1  Steel pan     7.26
         2  Ceramic mug  48.51
(2 rows)
UPDATE accounts SET balance_cents = balance_cents + 1000 WHERE account_id IN (1, 2)
RETURNING account_id, balance_cents;
account_id  balance_cents
----------  -------------
         1         193400
         2          53078
(2 rows)
UPDATE courses SET credits = credits + 1 WHERE course_id IN (1, 2)
RETURNING course_id, code, credits;
course_id  code     credits
---------  -------  -------
        1  MATH101        5
        2  MATH201        4
(2 rows)

One row comes back for each row changed, so you can see exactly what the statement touched, and how many rows.

4. DELETE ... RETURNING

The returned rows are the ones that were removed: a built-in record of what was deleted:

DELETE FROM reviews WHERE rating = 1 AND review_id <= 40
RETURNING review_id, product_id, rating;
review_id  product_id  rating
---------  ----------  ------
       23          18       1
       28          25       1
(2 rows)
DELETE FROM audit_log WHERE note IS NULL AND log_id <= 20
RETURNING log_id, table_name, action;
log_id  table_name  action
------  ----------  ------
     1  cards       update
     2  accounts    delete
     6  cards       insert
     7  loans       update
     8  customers   update
    19  accounts    update
(6 rows)
DELETE FROM attendance WHERE status = 'absent' AND student_id = 1
RETURNING student_id, section_id, class_date, status;
student_id  section_id  class_date  status
----------  ----------  ----------  ------
         1          41  2025-03-04  absent
(1 row)

If you keep the returned rows (for example in a log), a mistaken delete can be traced and repaired.

5. RETURNING with an upsert

RETURNING works with the upsert of lesson 5.6, so you can see which rows were inserted or updated:

CREATE TABLE stock_levels (item TEXT PRIMARY KEY, qty INTEGER NOT NULL);
INSERT INTO stock_levels VALUES ('pen', 10);
INSERT INTO stock_levels (item, qty) VALUES ('pen', 5), ('ink', 7)
ON CONFLICT (item) DO UPDATE SET qty = qty + excluded.qty
RETURNING item, qty;
item  qty
----  ---
pen    15
ink     7
(2 rows)
CREATE TABLE stock_levels (item TEXT PRIMARY KEY, qty INTEGER NOT NULL);
INSERT INTO stock_levels VALUES ('pen', 10);
INSERT INTO stock_levels (item, qty) VALUES ('pen', 5), ('ink', 7)
ON CONFLICT (item) DO UPDATE SET qty = qty + excluded.qty
RETURNING item, qty;
item  qty
----  ---
pen    15
ink     7
(2 rows)
CREATE TABLE stock_levels (item TEXT PRIMARY KEY, qty INTEGER NOT NULL);
INSERT INTO stock_levels VALUES ('pen', 10);
INSERT INTO stock_levels (item, qty) VALUES ('pen', 5), ('ink', 7)
ON CONFLICT (item) DO UPDATE SET qty = qty + excluded.qty
RETURNING item, qty;
item  qty
----  ---
pen    15
ink     7
(2 rows)

The pen row was updated (10 + 5), the ink row was inserted.

6. What you can return

RETURNING can return any column of the changed rows, expressions and aliases, or * for all columns:

INSERT INTO stock_levels (item, qty) VALUES ('tape', 3) RETURNING *, qty * 2 AS double_qty;
item  qty  double_qty
----  ---  ----------
tape    3           6
(1 row)
INSERT INTO stock_levels (item, qty) VALUES ('tape', 3) RETURNING *, qty * 2 AS double_qty;
item  qty  double_qty
----  ---  ----------
tape    3           6
(1 row)
INSERT INTO stock_levels (item, qty) VALUES ('tape', 3) RETURNING *, qty * 2 AS double_qty;
item  qty  double_qty
----  ---  ----------
tape    3           6
(1 row)

In other databases. PostgreSQL's documentation says INSERT has an optional RETURNING clause that returns values for each row inserted (or updated by ON CONFLICT DO UPDATE), and calls it a PostgreSQL extension. The MySQL INSERT documentation page shows no RETURNING clause. SQLite supports it from version 3.35.0 (the browser's SQLite is newer). This comes from the official documentation and was not run here. Where a database lacks RETURNING, a program asks for the new id with a separate function or query.

Worked example: create an order and its first line

Step Statement
1 INSERT INTO orders (customer_id, ...) VALUES (...) RETURNING order_id;
2 the program reads order_id from the result, for example 2601
3 INSERT INTO order_items (order_id, line_no, ...) VALUES (2601, 1, ...);

Without RETURNING the program would run a second query to find the id, and a concurrent insert could confuse it. The tables are from the Shop sample.

Common mistakes

  • Expecting RETURNING in every database.
  • Ignoring the returned rows, then running another query for the same information.
  • Forgetting that UPDATE ... RETURNING shows the new values.
  • Using RETURNING on a statement that changes no rows: the result is empty.

Key takeaways

  • RETURNING gives back rows from INSERT, UPDATE and DELETE in the same statement.
  • It returns the new id and the defaults the database filled in.
  • After UPDATE it shows new values; after DELETE, the removed rows.
  • Support differs between databases.

Practice

1. How do you get the id of a new row without a second query?

Show answer

Add RETURNING id (with the real id column) to the INSERT.

2. What does DELETE ... RETURNING * return?

Show answer

The rows that were deleted, with all their columns.

3. Which values does UPDATE ... RETURNING price show?

Show answer

The prices after the update.

4. Why is RETURNING better than a second SELECT?

Show answer

It saves a round trip, and nothing can change the rows between the statement and the query.

5. What if the database does not support RETURNING?

Show answer

Use that database's own way to read the new id or the changed rows, such as a separate function or query.

6. How many rows come back from an update that changed 3 rows?

Show answer

Three, one for each changed row.