SQL Tutorial · Changing Data and Tables · Lesson 29 of 36
SQL DELETE
Remove rows safely, and understand TRUNCATE and soft deletes.
DELETE FROM ... WHERE
SELECT COUNT(*) AS before FROM orders;
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 after FROM orders;
Output
before 12 after 11
Like UPDATE, a DELETE without WHERE removes every row. Run the same WHERE as a SELECT first.
Foreign keys
You can't delete a row that other rows still reference when foreign keys are enforced — delete the children first, or declare ON DELETE CASCADE.
TRUNCATE and soft deletes
TRUNCATE TABLE t(PostgreSQL, MySQL) quickly empties a whole table.- Many apps use soft deletes — a
deleted_atcolumn — so data can be restored and audited.
Test yourself
Which statement removes rows from a table?
DROPDELETEREMOVEERASE
Show answer
Answer: DELETE