Sub topic 8
Removing Rows with `DELETE`
Prerequisites and the basic statement
Assume you know SELECT with WHERE, and that the example database has customers and orders tables. The tables use primary keys, and each order refers to a customer through customer_id.
DELETE removes rows from a table. Its general form is:
DELETE FROM table_name
WHERE condition;The WHERE clause identifies the rows to remove. Without WHERE, the statement removes every row in the table.
DELETE FROM orders
WHERE id = 100;This removes the order whose id is 100. If no such order exists, no rows are removed. If id is unique, at most one row is affected.
A delete does not remove the table itself. The columns, indexes, and constraints remain. Only matching rows disappear.
Preview the rows first
A safe habit is to run a SELECT with the same condition before running DELETE.
SELECT id, customer_id, total, status
FROM orders
WHERE status = 'cancelled';
DELETE FROM orders
WHERE status = 'cancelled';The SELECT lets you inspect the exact rows. Many database tools also report the number of rows affected by DELETE. Compare that number with your expectation.
When checking for missing values, use IS NULL, not = NULL:
SELECT id, name
FROM customers
WHERE email IS NULL;
DELETE FROM customers
WHERE email IS NULL;NULL means an unknown or missing value. Comparisons with NULL do not produce true, so email = NULL will not select those rows.
Delete several rows safely
A condition can combine several rules:
DELETE FROM orders
WHERE status = 'cancelled'
AND total = 0;This removes only cancelled, zero-value orders. If the condition is complex, preview it with a query that returns the expected count:
SELECT COUNT(*) AS rows_to_remove
FROM orders
WHERE status = 'cancelled'
AND total = 0;You can also use a key list:
DELETE FROM orders
WHERE id IN (101, 102, 103);Prefer stable identifiers such as primary keys when possible. A condition based on a mutable value, such as a name, might match more rows than intended.
`DELETE` versus `TRUNCATE`
DELETE can target selected rows and normally records each row-level change. TRUNCATE removes all rows from a table as one table-level operation in systems that support it. Its transaction behavior, identity-counter behavior, and foreign-key restrictions vary by database.
| Operation | Selective rows | Can use `WHERE` | Typical use |
|---|---|---|---|
| `DELETE` | Yes | Yes | Remove matching data |
| `TRUNCATE` | No | No | Empty a whole table quickly |
Use DELETE when you need a condition or when foreign-key and transaction behavior must be controlled carefully.
Exercise
What rows does this statement remove, and what should you do before running it? DELETE FROM orders WHERE status = 'cancelled';
Show answer
It removes every cancelled order. First run SELECT * FROM orders WHERE status = 'cancelled'; and verify that all returned rows should be deleted.