Memra

UPDATE and DELETE

◈ 2 cards

Change and remove rows — carefully.

Change and remove

UPDATE changes columns in rows that match WHERE; DELETE removes matching rows. Both use RETURNING too:

UPDATE books SET price = price * 1.10
WHERE genre = 'poetry'
RETURNING title, price;
DELETE FROM reviews WHERE stars < 3 RETURNING id;

Note you can't DELETE a book that an order still references — the foreign key protects it. The database refuses to orphan the order_items rows that point at it. That's referential integrity doing its job.

titlegenreprice beforeprice afterNorthern Lightpoetry9.9910.99Saltwater Hymnspoetry11.0012.10The other eight books are untouched.
UPDATE books SET price = price * 1.10 WHERE genre = 'poetry'. Two rows match, so two rows change — RETURNING title, price hands them straight back for checking.
statementrows hitwhat happensUPDATE … WHERE genre ='poetry'2the two poetry booksUPDATE … (no WHERE)10every book repricedDELETE FROM reviews WHEREstars < 31review 6, the 2-star oneDELETE FROM books WHERE id= 10refused: order_items pointsat itA missing WHERE is not an error. It is ten rows.
A missing WHERE is not a syntax error and raises nothing — it simply matches every row. The only statement the database refuses outright is the one that would orphan existing rows.
NORMAL ~/memra/learn/postgresql/update-delete utf-8 LF