Video in progress

What does the `RETURNING` clause give you in PostgreSQL?

RETURNING immediately returns the columns of the rows affected by an INSERT, UPDATE or DELETE. For example, you don't need a separate SELECT to get the newly generated id or the updated value.

📖 Answer

INSERT INTO orders (user_id, total)
VALUES (42, 150000)
RETURNING id, created_at;

One query means one round trip to the database. If you run a separate SELECT, you have to think about which condition to use, and another transaction can slip in between.

It's very handy with UPDATE too:

UPDATE coupons
SET used_count = used_count + 1
WHERE code = 'NOV10' AND used_count < max_uses
RETURNING used_count;

If no row comes back, the coupon limit is used up. The check and the update happen in one atomic statement.

With DELETE it's useful for moving the deleted rows to an archive:

WITH moved AS (
    DELETE FROM sessions WHERE expires_at < now() RETURNING *
)
INSERT INTO sessions_archive SELECT * FROM moved;

In JDBC you run a query with RETURNING through executeQuery() and read from the ResultSet. Hibernate uses this mechanism, or getGeneratedKeys, to fetch IDENTITY ids.