Sub topic 13
Changing and Removing Rows Safely
This chapter assumes you can connect to a database with psql, that you have the books table from the earlier chapters, and that you can run SELECT with WHERE. If your table is missing, the setup block below recreates it.
UPDATE and DELETE change data that already exists. Both act on every row that matches their WHERE clause. If you leave the clause out, they act on every row in the table. Most data-loss accidents in practice come from this one omission, so this chapter is mostly about habits that prevent it.
Setting up a known state
Run this in your practice database. It drops and recreates the table so every example gives the output shown.
DROP TABLE IF EXISTS books;
CREATE TABLE books (
id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title text NOT NULL,
author text NOT NULL,
published_year integer
);
INSERT INTO books (title, author, published_year)
VALUES
('Dune', 'Frank Herbert', 1965),
('Neuromancer', 'William Gibson', 1984),
('Emma', 'Jane Austen', 1815);
SELECT * FROM books ORDER BY id;The last query should return three rows with ids 1, 2 and 3.
How UPDATE works
UPDATE has three parts: the table, a SET list of new values, and a WHERE clause that selects rows.
UPDATE books SET published_year = 1966 WHERE title = 'Dune';PostgreSQL replies with a command tag:
UPDATE 1The number is the count of rows changed. Read it every time. If you expected one row and see UPDATE 0, your condition matched nothing, often because of a typo or different capitalization. If you see UPDATE 3 when you expected one, stop and read the next sections.
You can set several columns in one statement by separating the assignments with commas:
UPDATE books
SET title = 'Dune (Novel)', published_year = 1965
WHERE id = 1;An assignment can also use the current value of a column. This statement adds one to the year of every book published before 1900:
UPDATE books SET published_year = published_year + 1 WHERE published_year < 1900;Because the right-hand side is evaluated against the row's old values, the result is predictable even when several columns depend on each other.
How DELETE works
DELETE removes whole rows. It has no SET list, only a table and a WHERE clause.
DELETE FROM books WHERE title = 'Emma';The reply is DELETE 1, again a count of affected rows. There is no recycle bin. After the statement commits, the only way back is a backup.
Why the WHERE clause matters
Compare these two statements:
UPDATE books SET published_year = 2000;
UPDATE books SET published_year = 2000 WHERE id = 2;The first one sets every book to the year 2000. PostgreSQL does not ask for confirmation, because the statement is valid SQL. The second changes one row.
Choosing a safe condition
How you identify rows matters as much as having a clause at all.
- Use the primary key when you can.
WHERE id = 2matches at most one row, because primary keys are unique. - Be careful with non-unique columns.
WHERE author = 'Jane Austen'matches every book by that author, which may be more than you intend. - Watch for exact text. Comparison with
=is case sensitive fortextcolumns, so'dune'does not match'Dune'. - Be careful with
NULL.WHERE published_year = NULLnever matches anything. UseIS NULLinstead.
SELECT id, title FROM books WHERE published_year IS NULL;The preview habit: SELECT first
The simplest safety technique is to write the WHERE clause in a SELECT first. You see exactly which rows it matches. Then you reuse the same clause in the UPDATE or DELETE.
-- Step 1: preview
SELECT id, title, published_year FROM books WHERE published_year < 1900;
-- Step 2: change only after the preview looks right
UPDATE books SET published_year = 1816 WHERE published_year < 1900;If the preview returns the rows you expected, and the count in the command tag matches the number of preview rows, the change did what you intended.
Transactions: a way to undo
By default, psql runs each statement in its own transaction and commits it at once (this is called autocommit). You can take control with BEGIN. Until you run COMMIT, your changes are visible only to your own session, and ROLLBACK discards them.
BEGIN;
DELETE FROM books WHERE published_year < 1900;
SELECT id, title FROM books ORDER BY id;
ROLLBACK;
SELECT id, title FROM books ORDER BY id;The first SELECT shows the table without the old books. After ROLLBACK, the second SELECT shows all three rows again. When you are happy with the result, run COMMIT in place of ROLLBACK.
If a statement inside a transaction fails, PostgreSQL marks the transaction as aborted. Every later command returns current transaction is aborted, commands ignored until end of transaction block. Run ROLLBACK to clear the state and start again.
RETURNING: see what changed
Both UPDATE and DELETE accept a RETURNING clause. It prints the affected rows, so you see them without a separate query.
UPDATE books
SET published_year = 1967
WHERE id = 1
RETURNING id, title, published_year;
DELETE FROM books
WHERE id = 3
RETURNING id, title;RETURNING is a PostgreSQL feature that many other databases lack. It is useful inside a transaction, because you can review the exact rows before you commit.
Common errors
| Symptom | Likely cause | What to do |
|---|---|---|
| `UPDATE 0` or `DELETE 0` | The condition matched no rows (typo, wrong case, `= NULL`) | Run the same condition in a `SELECT` and fix it |
| Far more rows changed than expected | Missing `WHERE`, or a condition on a non-unique column | If you used `BEGIN`, run `ROLLBACK`. Otherwise restore from a backup |
| `column "xyz" does not exist` | A string value written with double quotes | Use single quotes for text values. Double quotes name identifiers |
| `current transaction is aborted` | An earlier statement failed inside `BEGIN` | Run `ROLLBACK` and retry |
| `null value in column ... violates not-null constraint` | Setting a `NOT NULL` column such as `title` to `NULL` | Provide a real value |
The double-quote error is easy to trigger. Compare:
UPDATE books SET title = 'Dune' WHERE id = 1;
UPDATE books SET title = "Dune" WHERE id = 1;The first works. In the second, PostgreSQL reads "Dune" as a column name and fails.
A note on identity ids
Deleting a row does not free its id for reuse. The GENERATED ALWAYS AS IDENTITY column keeps counting upward. If you delete the book with id 3 and then insert a new row, the new row gets id 4. Gaps in ids are normal and harmless.
Putting it together
This full session follows the safe pattern: preview, open a transaction, change, verify, then commit.
SELECT id, title FROM books WHERE title = 'Emma';
BEGIN;
DELETE FROM books WHERE title = 'Emma' RETURNING id, title;
SELECT count(*) FROM books;
COMMIT;If the DELETE had reported the wrong number of rows, you would have typed ROLLBACK instead of COMMIT, and nothing would have changed.
Exercise
You run UPDATE books SET author = 'Anonymous'; and PostgreSQL replies UPDATE 3. What went wrong, what should you have done before running it, and how could you have undone it?
Show answer
The statement had no WHERE clause, so it changed the author of all three rows. Before running it, you should have written the intended condition in a SELECT to preview the matching rows, and checked that the count matched. You could have undone it by running BEGIN; first and then ROLLBACK; after seeing the wrong count. Because the statement ran in autocommit mode, the change is already saved, and recovering the old values would require a backup.
Exercise
Write a statement that deletes the book with id 2 and prints the title of the deleted row, in a way that lets you cancel before the delete is saved.
Show answer
BEGIN; DELETE FROM books WHERE id = 2 RETURNING title; -- If the result is correct, run COMMIT; otherwise run ROLLBACK;