DELETE
What it means
Section titled βWhat it meansβDELETE removes rows from a table, optionally restricted by a WHERE clause. Without a WHERE clause, it removes every row in the table (unlike TRUNCATE, itβs logged row-by-row and can trigger DELETE triggers, but is otherwise just as capable of wiping the whole table).
Examples
Section titled βExamplesβDELETE FROM Orders WHERE Id = 42;
DELETE FROM Orders WHERE OrderDate < '2020-01-01';
-- Delete based on a join / subquery conditionDELETE FROM OrdersWHERE CustomerId IN (SELECT Id FROM Customers WHERE IsBanned = 1);
-- DANGER: removes every row in the tableDELETE FROM Orders;Common mistake
Section titled βCommon mistakeβRunning DELETE FROM TableName; without a WHERE clause, intending to delete only some rows but forgetting the condition β this silently and irreversibly wipes the entire table with no confirmation prompt.
-- Intended to delete one customer's orders, but forgot the WHERE clause entirelyDELETE FROM Orders; -- deletes ALL orders, for every customer
-- CorrectDELETE FROM Orders WHERE CustomerId = 42;
-- Best practice: run the equivalent SELECT first to verify what would be affectedSELECT * FROM Orders WHERE CustomerId = 42; -- check this looks right, THEN deleteQuick practice
Section titled βQuick practiceβ-
What happens if you run
DELETE FROM Orders;with noWHEREclause?Answer
Every row in theOrderstable is deleted. -
Whatβs a safe habit before running a
DELETEwith aWHEREclause on production data?Answer
Run the equivalentSELECTwith the sameWHEREclause first, to verify exactly which rows would be affected before actually deleting them. -
Can a
DELETEstatementβsWHEREclause reference a subquery?Answer
Yes β e.g.DELETE FROM Orders WHERE CustomerId IN (SELECT Id FROM Customers WHERE IsBanned = 1);