SQL DELETE
DELETE removes rows from a table.
DELETE FROM table_name
WHERE condition;Like UPDATE, the WHERE clause decides which rows are affected — and without it, all rows are deleted.
Deleting specific rows
TAD Market decides to purge cancelled orders. First look, then delete:
SELECT COUNT(*) AS cancelled FROM orders WHERE status = 'cancelled';
DELETE FROM orders WHERE status = 'cancelled';
SELECT status, COUNT(*) AS orders FROM orders GROUP BY status ORDER BY status;cancelled
---------
7
(1 row)
7 rows affected.
status | orders
-----------+-------
delivered | 16
processing | 8
shipped | 9
(3 rows)
Deleting one row by key
The safest delete targets the primary key:
DELETE FROM order_items WHERE item_id = 98;
SELECT item_id, product_id, quantity
FROM order_items
WHERE order_id = 40
ORDER BY item_id;1 row affected.
item_id | product_id | quantity
--------+------------+---------
97 | 17 | 5
(1 row)
Deleting all rows
DELETE FROM table without WHERE empties the table but keeps its structure, so you can insert again:
DELETE FROM order_items;
SELECT COUNT(*) AS items_left FROM order_items;98 rows affected.
items_left
----------
0
(1 row)
| Statement | Removes | Table still exists? |
|---|---|---|
DELETE FROM t WHERE … |
matching rows | yes |
DELETE FROM t |
all rows | yes |
TRUNCATE TABLE t (MySQL, PostgreSQL, SQL Server) |
all rows, faster, no WHERE | yes |
DROP TABLE t |
the whole table | no |
SQLite has no TRUNCATE; DELETE FROM t without WHERE is optimised to do the same job.
Deleting rows that depend on others
Deleting orders leaves their order_items behind ("orphans") unless foreign keys are enforced with ON DELETE CASCADE. Here we remove the items of cancelled orders first, then the orders, using a subquery:
DELETE FROM order_items
WHERE order_id IN (SELECT order_id FROM orders WHERE status = 'cancelled');
DELETE FROM orders WHERE status = 'cancelled';
SELECT COUNT(*) AS orders, (SELECT COUNT(*) FROM order_items) AS items
FROM orders;20 rows affected.
7 rows affected.
orders | items
-------+------
33 | 78
(1 row)
Tip: In real systems, wrap multi-step deletes in a transaction (
BEGIN … COMMIT) so they succeed or fail together. You will learn this in the Transactions lesson. Many applications prefer a soft delete — a column likeis_deleted— instead of removing rows for good.
Test yourself
What does DELETE FROM customers; do?
- Drops the customers table
- Removes all rows but keeps the table
- Removes the first row
- Raises an error
Which statement removes a table completely, including its structure?
- DELETE FROM t
- TRUNCATE t
- DROP TABLE t
- REMOVE t