Sub topic 9
Previewing and Limiting the Rows You Change
Assume you know basic SELECT queries with WHERE, tables, rows, columns, primary keys, and foreign keys. This chapter focuses on a safety habit: preview the rows before changing them.
An UPDATE or DELETE can affect many rows. The WHERE clause determines which rows match. If you omit it, every row matches.
Preview an UPDATE
Suppose you want to mark all new orders as shipped. First run the same condition with SELECT:
SELECT id, customer_id, status
FROM orders
WHERE status = 'new';Review the returned rows. If they are correct, run the update:
UPDATE orders
SET status = 'shipped'
WHERE status = 'new';You can also count the rows before changing them:
SELECT COUNT(*) AS rows_to_change
FROM orders
WHERE status = 'new';The preview and the change must use equivalent conditions. Adding an extra condition to one statement changes the target set.
Preview a DELETE
Use the same approach before deleting:
SELECT id, customer_id, status
FROM orders
WHERE status = 'cancelled';If the result is correct, delete those rows:
DELETE FROM orders
WHERE status = 'cancelled';A useful rule is to write the SELECT first, then change only the first keyword and the selected columns when you are ready.
Limit the target set
A condition can still match more rows than intended. Add a more specific predicate when possible:
UPDATE orders
SET status = 'shipped'
WHERE id = 100
AND status = 'new';The second condition prevents an already shipped order from being changed accidentally.
Some database systems support LIMIT directly in data-changing statements, but the syntax differs by product. A portable approach is to identify exact keys first:
SELECT id
FROM orders
WHERE status = 'cancelled'
ORDER BY id
FETCH FIRST 10 ROWS ONLY;Then use those keys in a separate statement. FETCH FIRST is supported by several systems, while PostgreSQL and MySQL commonly use LIMIT. Always check your database's syntax before using a row limit in UPDATE or DELETE.
Use a transaction while testing
A transaction groups changes so you can inspect them before making them permanent:
BEGIN;
UPDATE orders
SET status = 'shipped'
WHERE status = 'new';
SELECT id, status
FROM orders
WHERE status = 'shipped';
ROLLBACK;ROLLBACK discards the change. Replace it with COMMIT only after verifying the result. If your database automatically commits each statement, explicitly start a transaction before testing.
The safest workflow is:
- Write the
WHEREcondition. - Preview matching rows with
SELECT. - Check the count and sample values.
- Run the change inside a transaction.
- Verify the result.
- Commit or roll back.
Exercise
What is the safest way to change only cancelled orders for customer 7?
Show answer
First run SELECT id, status FROM orders WHERE customerid = 7 AND status = 'cancelled'; then run DELETE FROM orders WHERE customerid = 7 AND status = 'cancelled'; inside a transaction, and commit only after verifying the preview.