Sub topic 9
Previewing and limiting the rows you change
This chapter assumes you can write a SELECT with a WHERE clause and that you know the customers and orders tables from earlier in the tutorial. It also assumes you know what INSERT, UPDATE, and DELETE do in their basic forms. Here you will build a routine that shows which rows a change will touch before it touches them, and that confirms afterward that it touched only those rows.
Why the WHERE clause carries the risk
UPDATE and DELETE apply to every row of the table unless a WHERE clause narrows them. The database does not ask for confirmation. A statement that omits WHERE, or has one that matches more than you meant, is valid SQL and runs successfully.
-- Intended: cancel one order. Actual: every order is now 'cancelled'.
UPDATE orders
SET status = 'cancelled';Constraints rarely stop this kind of mistake. Setting every status to 'cancelled' violates no rule, so the change goes through. Your own checking is the only protection.
The preview habit
A WHERE clause works the same in SELECT, UPDATE, and DELETE. Because of that, you can test the condition with a harmless SELECT first and then reuse it unchanged.
- Write a
SELECT COUNT(*)with the condition and compare the count with what you expect. - Write a
SELECTthat lists the rows, and read them. - Replace the
SELECTpart withUPDATE ... SETorDELETE, keeping theWHEREtext identical. - Run the change and compare the reported row count with the count from step 1.
SELECT COUNT(*)
FROM orders
WHERE status = 'new' AND total > 500;
SELECT id, customer_id, total, status
FROM orders
WHERE status = 'new' AND total > 500;
UPDATE orders
SET status = 'review'
WHERE status = 'new' AND total > 500;Previewing the new values
For an UPDATE that computes values, preview the result as well as the rows. Put the expression in the select list and give it an alias:
SELECT id, total AS old_total, total * 1.10 AS new_total
FROM orders
WHERE status = 'new';If a result looks wrong, such as a NULL or a number with unexpected rounding, you find out before any data changes.
Check the reported row count
Every client reports how many rows a statement changed. PostgreSQL prints UPDATE 3 or DELETE 3. MySQL prints "Rows matched" and "Changed" for updates. SQL Server prints "(3 rows affected)". Application drivers expose the same number, for example cursor.rowcount in Python.
If the preview said 3 and the statement reports 3,000, stop and investigate. A count of 0 is also a signal: the statement was valid but matched nothing, usually because of a typo in a value.
Conditions that match the wrong rows
Most bad changes come from a WHERE clause that is valid but does not say what the author thought. These are the common causes.
Comparing to NULL
NULL means "unknown", and any = comparison with it yields unknown, not true. A condition like this matches no rows at all:
SELECT id, name FROM customers WHERE email = NULL; -- returns nothing
SELECT id, name FROM customers WHERE email IS NULL; -- returns Alan TuringThe same applies to <> NULL and to status <> 'active'. The second condition skips rows where status is NULL, so a column that allows nulls can hide rows from a "not equal" filter.
AND and OR precedence
AND binds more tightly than OR. This condition does not mean "customer 7 and either status":
-- Matches: (status = 'new') OR (status = 'repriced' AND customer_id = 7)
DELETE FROM orders
WHERE status = 'new' OR status = 'repriced' AND customer_id = 7;Every 'new' order for every customer would be deleted. Add parentheses whenever you mix the two operators:
DELETE FROM orders
WHERE customer_id = 7
AND (status = 'new' OR status = 'repriced');Values that look equal but are not
String comparison depends on the database and column collation. In PostgreSQL, 'Active' and 'active' are different values. In MySQL with a default collation, they are equal. Trailing spaces and type conversions can also change what matches. The preview shows what the database actually matches, so trust it over your reading of the condition.
A condition that is too broad
WHERE total > 0 or WHERE status LIKE '%e%' can match nearly everything. When you expected a handful of rows, check the count before anything else.
Limiting the blast radius
Target by primary key
When you intend to change one row, filter on the primary key. The key is unique, so WHERE id = 100 can match at most one row, whatever else is in the data. A condition on a non-unique column such as status or name can match many.
Cap the number of rows
Sometimes you want to change a bounded batch, for example to purge old rows in pieces so a large delete does not hold locks for long. Dialects differ here:
| Database | Cap on `UPDATE` or `DELETE` |
|---|---|
| MySQL | `DELETE FROM orders WHERE status = 'cancelled' ORDER BY id LIMIT 100;` |
| SQL Server | `DELETE TOP (100) FROM orders WHERE status = 'cancelled';` |
| PostgreSQL | No `LIMIT` on the statement. Select the keys in a subquery. |
| SQLite | `LIMIT` works only if SQLite was compiled with that option. The subquery form is portable. |
The subquery form works in PostgreSQL and SQLite:
DELETE FROM orders
WHERE id IN (
SELECT id
FROM orders
WHERE status = 'cancelled'
ORDER BY id
LIMIT 100
);Always pair LIMIT or TOP with an ORDER BY. Without one, the database picks any 100 matching rows, and a repeated run may choose differently.
Safe-update modes
MySQL has a client safeguard called safe updates mode. It is enabled with SET sql_safe_updates = 1; or the --safe-updates client option. In that mode, an UPDATE or DELETE that has no WHERE clause on a key column, and no LIMIT, is rejected with error 1175. Other databases have no direct equivalent, so the preview habit is the portable protection.
Gaps between the preview and the change
The preview only describes the data at the moment you ran it. If other sessions are writing to the same table, rows can change between your SELECT and your UPDATE, and the two can disagree. A transaction lets you inspect the result of the real statement and undo it, which is the topic of the next chapter.
Summary of the routine
- Count and list the rows with the same
WHEREclause before changing anything. - Use parentheses when mixing
ANDandOR, andIS NULLfor null checks. - Filter on the primary key when you mean one row.
- Compare the reported row count with the preview count.
- Cap batch size with the syntax your database supports, and always add
ORDER BYwith it.
Exercise
A teammate runs DELETE FROM orders WHERE customer_id = 3 OR customer_id = 4 AND status = 'cancelled'; intending to delete only cancelled orders for customers 3 and 4. Which rows does it actually delete, and how would you correct it?
Show answer
Because AND binds before OR, the condition means customerid = 3 (any status) OR (customerid = 4 AND status = 'cancelled'). It deletes every order of customer 3 plus only the cancelled orders of customer 4. The fix is WHERE status = 'cancelled' AND (customer_id = 3 OR customer_id = 4), or customer_id IN (3, 4). Preview it first with SELECT COUNT(*) and the same condition.
Exercise
You want to set status = 'inactive' for every customer with no email address. You run UPDATE customers SET status = 'inactive' WHERE email = NULL; and the client reports 0 rows affected. Why, and what should you write instead?
Show answer
Comparing a value to NULL with = gives unknown, never true, so no row matches. Use WHERE email IS NULL. Preview with SELECT id, name FROM customers WHERE email IS NULL; before running the update.