Skip to content

Updating and deleting

The last two CRUD verbs change existing data. UPDATE sets new column values on rows that match a condition, and DELETE removes matching rows. Both lean heavily on the WHERE clause you learned for SELECT — and both become destructive mistakes if you forget it.

We continue with the authors and books tables.

UPDATE names the table, lists SET column = value pairs, and uses WHERE to pick the rows. Without WHERE, every row is changed.

UPDATE books
SET copies_sold = copies_sold + 500
WHERE id = 1;

The new value can reference the old one, as copies_sold + 500 shows. You can set several columns at once by separating the assignments with commas.

In pgAdmin: run this in the Query Tool; the message panel reports UPDATE 1, the count of rows changed.

Just like INSERT, both UPDATE and DELETE accept RETURNING. This is the cleanest way to see exactly which rows changed and what their new values are.

UPDATE books
SET published = 2005
WHERE title = 'The Glass Orchard'
RETURNING id, title, published;
id | title | published
----+-------------------+-----------
1 | The Glass Orchard | 2005
(1 row)

DELETE FROM removes rows that match the WHERE clause. Like UPDATE, you can add RETURNING to see what was removed.

DELETE FROM books
WHERE copies_sold = 0
RETURNING id, title;
id | title
----+----------------
3 | Quiet Harbors
(1 row)

UPDATE and DELETE apply to every row that matches the condition — and if there is no condition, every row matches. Running DELETE FROM books; empties the entire table, and UPDATE books SET copies_sold = 0; zeroes every record. There is no undo button.

A safe habit is to run the same WHERE as a SELECT first, confirm the row count, then switch the verb. Wrapping risky changes in a transaction gives you an escape hatch.

BEGIN;
DELETE FROM books WHERE author_id = 4;
-- inspect the result, then decide:
ROLLBACK; -- or COMMIT; to keep the change

Inside a transaction, nothing is permanent until you COMMIT; a ROLLBACK throws the changes away. Transactions get a full lesson of their own later in the course.

  • Always include a WHERE clause on UPDATE and DELETE unless you genuinely intend to touch every row. A forgotten WHERE rewrites or empties the whole table.
  • Preview destructive statements by running the matching SELECT count(*) ... WHERE ... first to confirm how many rows you are about to affect.
  • Wrap risky or multi-step changes in a transaction so you can ROLLBACK if the result is wrong.
  • Use RETURNING to verify exactly which rows changed instead of trusting the row count alone.
  • A DELETE may fail if other tables reference the row through a foreign key; you will revisit this in the joins and relationships module.
What happens if you run UPDATE books SET copies_sold = 0; with no WHERE clause?
Which clause lets an UPDATE or DELETE report exactly which rows it changed?
How can you make a risky DELETE reversible while you check the result?