AI Hints
Home›PostgreSQL Tutorial›Foreign Keys and RETURNING
PostgreSQL · Lesson 21 of 120

UPDATE and DELETE ... RETURNING

Change and see.

⏱ 2 min read▶ Video at 17:44🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

Prices change, and old events get removed. Update and delete change rows. Always use a where clause, or you'll change every row in the table.

  • UPDATE
  • DELETE
  • Always WHERE

Raise prices, see the result

Update sets a new price, ten percent higher, only for cooking books. Returning shows the new prices. Run it. Every cooking book, with its new price.

query.sqlsql
UPDATE books
SET price = round(price * 1.10, 2)
WHERE genre = 'Cooking'
RETURNING title, price;
Output
       title       | price
-------------------+-------
 The Quiet Kitchen | 27.49
 Spice Roads       | 30.79
 One Pan Dinners   | 23.64
(3 rows)

UPDATE 3

Delete and return

Delete removes rows that match where. Returning shows exactly what was removed, which is great for logs. Run it. The one event with fewer than twenty five seats, deleted.

query.sqlsql
DELETE FROM events
WHERE seats < 25
RETURNING *;
Output
 event_id |      title      | seats
----------+-----------------+-------
        2 | Kids Story Hour |    20
(1 row)

DELETE 1
Also uses _setup.sql
CREATE TABLE events (
  event_id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  title    text NOT NULL,
  seats    integer NOT NULL CHECK (seats > 0));
INSERT INTO events (title, seats) VALUES ('Poetry Night', 30), ('Kids Story Hour', 20);

Summary

Update and delete change rows that match where, and returning shows what changed. Next, insert or update in one step.

Key takeaways
  • UPDATE
  • DELETE
  • WHERE!
Next up: Upsert with ON CONFLICT — insert or update