← Back to PostgreSQL Course | Chapter 4: Inserting & Modifying Data | Lesson 5 of 7

RETURNING clause

RETURNING gives you the rows that were inserted, updated or deleted, without a second query.

In this page:

  1. RETURNING clause
Syntax
sql
INSERT INTO table_name (column) VALUES (value) RETURNING columns;
UPDATE table_name SET column = value WHERE condition RETURNING columns;

RETURNING clause

Add RETURNING columns to INSERT, UPDATE or DELETE and PostgreSQL returns those columns for the affected rows. It is perfect for fetching generated ids (RETURNING id) or the new values after an update.

RETURNING * returns whole rows. This is a PostgreSQL feature (SQLite only supports it in versions 3.35 and later).

Note:
  • INSERT ...
  • RETURNING id is the standard way to get a new id in PostgreSQL.

Example: RETURNING clause

bash
shop=# INSERT INTO users (name, email) VALUES ('Ada', '[email protected]') RETURNING id, created_at;
 id |          created_at
----+-------------------------------
  1 | 2024-03-15 10:30:11.123456+00
(1 row)
INSERT 0 1

shop=# UPDATE users SET name = 'Ada L.' WHERE id = 1 RETURNING *;
 id |  name  |      email      |          created_at
----+--------+-----------------+-------------------------------
  1 | Ada L. | [email protected] | 2024-03-15 10:30:11.123456+00
UPDATE 1

shop=# DELETE FROM users WHERE id = 1 RETURNING name;
  name
--------
 Ada L.
DELETE 1

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
Common Mistakes
  1. Running a second SELECT to get the new id
  2. Forgetting RETURNING returns rows to the client
  3. Expecting it in every database
Chapter Summary
  • RETURNING returns affected rows
  • Works on INSERT, UPDATE and DELETE
  • RETURNING id gets generated ids
  • RETURNING * returns whole rows
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.