TExcelTAD
Home › SQL › SQL DELETE

SQL DELETE

DELETE removes rows from a table.

sql
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:

sql · try it yourself
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:

sql · try it yourself
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:

sql · try it yourself
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:

sql · try it yourself
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 like is_deleted — instead of removing rows for good.

Test yourself

What does DELETE FROM customers; do?

  1. Drops the customers table
  2. Removes all rows but keeps the table
  3. Removes the first row
  4. Raises an error

Which statement removes a table completely, including its structure?

  1. DELETE FROM t
  2. TRUNCATE t
  3. DROP TABLE t
  4. REMOVE t