Sub topic 8
Removing rows with DELETE
DELETE removes whole rows from a table. This chapter assumes you can write a SELECT with a WHERE clause, and that you know what primary keys and foreign keys are. It also assumes you have the customers and orders tables from the first chapter, with customers 1, 2 and 3 inserted. Later chapters cover transactions, foreign key actions, TRUNCATE, and RETURNING in more depth. Here we focus on how DELETE itself behaves.
The basic form
DELETE FROM table_name
WHERE condition;DELETE works on whole rows. It cannot remove a single column's value from a row. To clear one column, use UPDATE and set it to NULL. The WHERE clause is the same kind you use in SELECT. Each row is tested, and DELETE removes the rows for which the condition is true.
To follow along, add some orders for the existing customers:
INSERT INTO orders (id, customer_id, total, status)
VALUES
(100, 1, 40.00, 'shipped'),
(101, 1, 15.50, 'cancelled'),
(102, 2, 99.99, 'cancelled'),
(103, 2, 10.00, 'new'),
(104, 3, 70.00, 'new');Now remove the cancelled orders:
SELECT COUNT(*) FROM orders WHERE status = 'cancelled';
DELETE FROM orders
WHERE status = 'cancelled';The SELECT returns 2, and the DELETE removes orders 101 and 102. Running the same condition in a SELECT first is the most useful safety habit for deletes. The count tells you what to expect before anything is gone.
What happens without WHERE
If you leave out WHERE, every row matches.
DELETE FROM orders;This empties the table. The table, its columns and its constraints stay in place. Only the rows are gone. Most database tools run this without asking, so check the statement before you execute it.
How the database reports the result
After a DELETE, the database tells you how many rows it removed. The wording differs by tool:
| System | Typical message |
|---|---|
| PostgreSQL (`psql`) | `DELETE 2` |
| MySQL | `Query OK, 2 rows affected` |
| SQL Server | `(2 rows affected)` |
| SQLite shell | No message by default. Run `SELECT changes();` afterward. |
Read this number every time and compare it with your expected count. If you expected 2 and the tool says 5, the condition was wrong. Application code can read the same value, which most database drivers expose as a "rows affected" property.
Deleting zero rows is not an error
If no row matches, DELETE succeeds and reports 0 rows.
DELETE FROM orders
WHERE id = 99999;This is easy to miss. A typo in a value, such as status = 'canceled' instead of 'cancelled', does not raise an error. It silently deletes nothing. When a script depends on a row being removed, check that the count is greater than zero.
Writing conditions carefully
DELETE uses the same condition logic as SELECT, so the same pitfalls apply.
AND and OR precedence
AND is evaluated before OR. These two statements are not the same:
-- Deletes all cancelled orders, plus new orders under 20
DELETE FROM orders
WHERE status = 'cancelled' OR status = 'new' AND total < 20;
-- Deletes only cancelled or new orders that are under 20
DELETE FROM orders
WHERE (status = 'cancelled' OR status = 'new') AND total < 20;When a condition mixes AND and OR, add parentheses so the intent is clear.
NULL needs IS NULL
A comparison with NULL is never true, so = NULL matches no rows. Use IS NULL.
DELETE FROM orders
WHERE customer_id IN (
SELECT id FROM customers WHERE email IS NULL
);This deletes the orders of customers with no email address. In our data that is order 104, which belongs to Alan Turing. Writing WHERE email = NULL in the subquery would match nothing, and the DELETE would remove 0 rows without any error.
The same rule has a second effect. A row whose condition evaluates to NULL is treated like a false one and is kept. For example, WHERE total < 20 never removes a row whose total is NULL. The total column in our schema is NOT NULL, but many real tables allow NULL in the columns you filter on.
Subqueries
WHERE can contain a subquery, as in the example above. Run the subquery as a standalone SELECT first to see which ids it returns.
Deleting by primary key
The safest DELETE targets a single row through its primary key.
DELETE FROM orders
WHERE id = 103;A primary key is unique, so this affects at most one row. If the tool reports 1 row, the statement did what you wanted. Prefer this form in application code, and build bulk deletes from a preview you have checked.
Rows referenced by other tables
A foreign key can block a delete. In our schema, orders.customer_id references customers.id. Try to delete a customer who still has orders:
DELETE FROM customers
WHERE id = 1;
-- Fails if order 100 still exists: orders.customer_id references this row.By default, the database rejects the statement and removes nothing. The error is a foreign key violation, and the message names the constraint. To fix it, delete the child rows first, or change the foreign key to use a cascading action. The later chapter on foreign keys covers those options. Delete in this order:
DELETE FROM orders WHERE customer_id = 1;
DELETE FROM customers WHERE id = 1;The reverse order fails on the first run, because the parent still has children when you try to remove it.
DELETE does not reset counters
Removing rows does not renumber the remaining rows or reset auto-generated ids. If a table uses an identity or auto-increment column, the next insert continues from the highest value ever issued, not from the highest remaining one. The id columns in our schema are supplied by hand, so this does not affect them. It does affect tables that generate ids. TRUNCATE can reset those counters in some systems, which is one reason it is covered separately.
Dialect notes
The DELETE FROM table WHERE condition form works in PostgreSQL, MySQL, SQL Server and SQLite. A few details vary:
- In SQL Server and PostgreSQL,
FROMis required in practice. SQL Server also allowsDELETE orders WHERE ...without it, but you should writeDELETE FROMfor portability. - MySQL's safe-updates mode, enabled in some clients, refuses a
DELETEwith noWHEREclause or no key-based condition. This is a client setting, not part of standard SQL. - Deleting based on a join, and limiting the number of rows deleted with
LIMITorTOP, are dialect-specific. A later chapter covers join-based deletes.
A safe workflow
- Write the condition as a
SELECT *orSELECT COUNT(*)and read the rows. - Change
SELECT ...toDELETEwhile keeping the sameWHEREtext. - Run it and compare the reported row count with the count from step 1.
- If the count differs, investigate before doing anything else. The next chapter section shows how a transaction lets you undo a delete.
Exercise
The orders table has rows with these statuses: 100 shipped, 103 new, 104 new. You run DELETE FROM orders WHERE status = 'canceled'; (spelled with one "l"). What does the database do, and how would you notice the mistake?
Show answer
The statement succeeds and deletes 0 rows, because no row has the status 'canceled' (the stored spelling is 'cancelled'). No error is raised. You would notice by reading the rows-affected message, which reports 0 instead of the count you expected from running SELECT COUNT(*) FROM orders WHERE status = 'canceled'; first.
Exercise
Write the two statements, in the correct order, that remove customer 2 and all of that customer's orders without violating the foreign key.
Show answer
DELETE FROM orders WHERE customer_id = 2; followed by DELETE FROM customers WHERE id = 2; The child rows in orders must go first. If you delete the customer first, the foreign key constraint rejects the statement while any order still references customer 2.