One statement instead of an INSERT followed by a SELECT - which also removes the race where another session changes the row in between.
INSERT INTO orders (customer_id, total)
VALUES (7, 99.00)
RETURNING id, created_at;
UPDATE orders SET status = 'PAID'
WHERE id = 8821 AND status = 'PENDING'
RETURNING id, status; -- empty result means it was not PENDING
DELETE FROM session WHERE expires_at < now() RETURNING id;
id | created_at
8822 | 2026-08-25 09:12:44+00
-- The UPDATE ... RETURNING pattern is a compare-and-set: an empty result
-- tells you the guard failed, without a second query and without a lock.
--
-- PostgreSQL, SQLite and MariaDB support RETURNING. MySQL does not - use
-- LAST_INSERT_ID() there.
Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.
Published 2026-08-25