1.SELECT, INSERT, UPDATE, DELETE and RETURNING
SELECT reads rows, INSERT adds them, UPDATE changes them, DELETE removes them. RETURNING attaches to a write to hand back the affected rows in the same round trip — no second query needed to see what happened.
Key features
- SELECT never modifies data — INSERT, UPDATE and DELETE all do
- INSERT ... RETURNING hands back the row(s) just inserted, including generated columns
- UPDATE without a WHERE clause changes every row in the table
- DELETE without a WHERE clause removes every row in the table
- RETURNING works on INSERT, UPDATE, DELETE — never SELECT, which has nothing extra to give
The four statements, and what RETURNING adds to each
- INSERT/UPDATE/DELETE — changes rows
- RETURNING * — hands back the affected rows
- result set — no second SELECT needed
Command
SELECT id, title FROM tasks WHERE done = false;
INSERT INTO tasks (title) VALUES ('Write docs') RETURNING id;
UPDATE tasks SET done = true WHERE id = 3 RETURNING *;
DELETE FROM tasks WHERE done = true RETURNING id;RETURNING hands back affected rows in the same round trip — the only way to see a deleted row's data, since a later SELECT never can.