Explain it simply
Explain it simply
DELETE removes lines from the ledger. The table itself and its columns stay; only the rows matching WHERE disappear. You use it to clear out cancelled orders, spam comments and expired login sessions.
As with UPDATE, WHERE is the lifeline: DELETE FROM customers; without a WHERE removes every customer. There is no recycle bin either; once committed, the only way back is a restore from backup, which may be hours old.
Problem → Why → Solution
The problem: cleaning spam wipes out every comment
A moderator writes a query to clean up spam comments. The first version uses OR instead of AND between the two conditions, so ordinary comments from yesterday are deleted too. In the second version a copy-paste puts the semicolon before the WHERE: every comment is deleted, and the WHERE line is left behind as a separate syntax error.
-- 1. OR instead of AND: every old comment AND every spam comment
DELETE FROM comments WHERE is_spam OR created_at < '2026-06-01';
-- 2. Stray semicolon: DELETE runs with no WHERE at all
DELETE FROM comments;
WHERE is_spam AND created_at < '2026-06-01'; -- syntax error, too lateWhy can't it be undone?
In autocommit mode each statement commits as soon as it finishes, and SQL has no "undo" command. DELETE does not judge your WHERE; it removes every row that matches. The routine of testing the WHERE with a SELECT, noting the row count, running DELETE ... RETURNING inside BEGIN and committing only if DELETE n matches catches both of these mistakes.
Core concept: rows matching WHERE disappear
Like UPDATE, DELETE FROM table WHERE condition first finds rows with the WHERE and then removes all of them. So SELECT * FROM table WHERE condition is an exact preview of what will disappear. A WHERE on the primary key can never remove more than one row. However many rows match, the statement is atomic: if a constraint error occurs, nothing is deleted. If nothing matches, there is no error, just DELETE 0.
Foreign keys protect DELETE. If orders.customer_id REFERENCES customers, deleting a customer who still has orders fails with "violates foreign key constraint", so no order is left without an owner. If the table was created with ON DELETE CASCADE, deleting the parent silently removes the child rows as well, which is as convenient as it is dangerous.
RETURNING (PostgreSQL) hands back the removed rows, which you can log, move to an archive table, or simply eyeball to confirm you deleted the right thing. Combined with BEGIN, you can still ROLLBACK before COMMIT. SQL Server has an OUTPUT clause and SQLite supports RETURNING, but MySQL has no DELETE ... RETURNING, so there you run the preview SELECT and keep its output instead.
In PostgreSQL, DELETE does not erase the row from disk immediately; it marks it as dead, and VACUUM later makes that space reusable. That is why deleting millions of rows does not shrink the table file right away. Autovacuum normally handles this in the background; only VACUUM FULL, which rewrites the table under an exclusive lock, actually returns the space to the operating system.
- SELECT the rows that will go
- Note the row count
- BEGIN; DELETE ... RETURNING
- Compare DELETE n with your note
- COMMIT or ROLLBACK
After COMMIT, only a backup can bring the rows back.
General pattern
SELECT count(*) FROM table_name WHERE condition; -- preview
BEGIN;
DELETE FROM table_name
WHERE condition
RETURNING key_column, other_column;
COMMIT; -- or ROLLBACK; if DELETE n is not what you expectedDELETE has no column list, because the whole row goes. The preview SELECT and the DELETE must share the same WHERE. RETURNING and BEGIN/COMMIT are optional, but on production data you should always use them.
Example: delete one customer safely
The customers table has four rows, and the orders table references customers 1 and 2. Around the Horn (id 4) has no orders, so it can be deleted. The example shows the whole routine: a preview SELECT, then DELETE ... RETURNING inside a transaction, then COMMIT.
CREATE TABLE customers (
customer_id integer PRIMARY KEY,
customer_name text NOT NULL,
country text
);
INSERT INTO customers VALUES
(1, 'Alfreds Futterkiste', 'Germany'),
(2, 'Ana Trujillo', 'Mexico'),
(3, 'Antonio Moreno', 'Mexico'),
(4, 'Around the Horn', 'UK');
CREATE TABLE orders (
order_id integer PRIMARY KEY,
customer_id integer NOT NULL REFERENCES customers (customer_id),
total numeric(8, 2) NOT NULL
);
INSERT INTO orders VALUES (101, 1, 45.00), (102, 2, 19.90), (103, 1, 249.00);-- 1. Preview: exactly the rows the DELETE will remove
SELECT customer_id, customer_name
FROM customers
WHERE customer_id = 4;
-- 2. Delete inside a transaction and show what was removed
BEGIN;
DELETE FROM customers
WHERE customer_id = 4
RETURNING customer_id, customer_name;
COMMIT;Code breakdown
- Preview
SELECT customer_id, customer_nameThe SELECT uses the same WHERE customer_id = 4 as the DELETE, so you know beforehand that only Around the Horn will disappear.
- BEGIN
BEGIN;Opening a transaction keeps a way back: until COMMIT, ROLLBACK can undo the delete. psql answers BEGIN.
- DELETE ... WHERE
DELETE FROM customers WHERE customer_id = 4Deleting by primary key removes at most one row. Customer 4 has no orders, so the foreign key does not object.
- RETURNING and COMMIT
RETURNING customer_id, customer_name;The removed row is shown and psql reports DELETE 1. It matches the preview, so COMMIT makes the change permanent.
customer_id | customer_name
-------------+-----------------
4 | Around the Horn
(1 row)
BEGIN
customer_id | customer_name
-------------+-----------------
4 | Around the Horn
(1 row)
DELETE 1
COMMITWhen a foreign key refuses the delete
Alfreds Futterkiste (id 1) has two orders. Trying to delete it raises an error and no row disappears. You have three options: delete the child rows first, define the foreign key with ON DELETE CASCADE (children vanish automatically), or do not delete the customer at all and use a soft delete instead.
-- ERROR: update or delete on table "customers" violates
-- foreign key constraint "orders_customer_id_fkey" on table "orders"
-- DELETE FROM customers WHERE customer_id = 1;
-- No matching row is not an error: 0 rows come back (DELETE 0)
DELETE FROM customers WHERE customer_id = 99 RETURNING customer_id;DELETE, TRUNCATE, DROP and soft delete
| Command | What happens | When to use it |
|---|---|---|
| DELETE ... WHERE | Removes matching rows; RETURNING and triggers work | Removing some rows selectively |
| TRUNCATE | Empties the whole table very fast; no WHERE | Clearing a staging or test table completely |
| DROP TABLE | Removes the table and its structure | The table is no longer needed at all |
| Soft delete | UPDATE ... SET deleted_at = now(); the row stays | Data needing history, audit or undo |
With soft deletes, every query must remember WHERE deleted_at IS NULL, which is why teams often wrap it in a view. PostgreSQL can also move rows into an archive table in one statement with a data-modifying CTE (CTEs are covered in a later lesson).
WITH moved AS (
DELETE FROM comments
WHERE is_spam
RETURNING *
)
INSERT INTO comments_archive
SELECT * FROM moved;In real projects
Where this shows up in real projects
Most teams never hard-delete business data such as user accounts, orders and invoices: they soft-delete with a deleted_at column and keep the rows for accounting and audits. When a user asks for account deletion under a privacy law such as GDPR, the personal columns must still be erased or anonymized, so deciding what is truly deleted, and when, is a design decision.
Temporary data such as login sessions, password reset tokens and job logs is cleared by a scheduled job running DELETE FROM sessions WHERE expires_at < now() every night. With millions of rows, one giant DELETE holds locks for a long time and writes a lot of WAL, so jobs delete in batches of a few thousand by id range. At very large volumes, partitioning the table by date and dropping a whole old partition is far faster than DELETE.
Common mistakes
Common mistakes
1. Writing OR where you meant AND
Writing "spam and old" as WHERE is_spam OR created_at < '2026-06-01' deletes all spam plus every old comment. Remember that OR widens a DELETE, and look at the preview SELECT's count: if you expected two spam rows and the count is 4, stop.
2. Deleting a parent row without knowing about CASCADE
If the foreign key is ON DELETE CASCADE, deleting one customer also removes their orders, payments and reviews, while RETURNING shows only the customers row. Check the schema before deleting from a parent table (in psql: \d orders).
3. Emptying a table with a bare DELETE on production
Running DELETE FROM orders; meant for a staging table on the production connection really happens. Check the database name in the psql prompt, connect to production with a read-only role by default, and when you do mean to empty a table, write TRUNCATE explicitly.
Best practices
Best practices
- Test the WHERE with SELECT count(*) before writing the DELETE.
- Delete production data only inside BEGIN, checking RETURNING and DELETE n.
- Soft-delete business data that may need history.
- Delete large volumes in small batches, and rehearse restoring from backup beforehand.
Mini challenge
Mini challenge: clean up old spam
Delete spam comments written before 2026-06-01 from the comments table. Normal comments and the June spam comment (cheap4u) must stay.
- Before deleting, show the number of rows that will go with SELECT count(*) (it must be 2)
- Run the DELETE between BEGIN and COMMIT
- Show comment_id and author with RETURNING
- A final SELECT shows the three remaining comments
CREATE TABLE comments (
comment_id integer PRIMARY KEY,
author text NOT NULL,
is_spam boolean NOT NULL,
created_at timestamp NOT NULL
);
INSERT INTO comments VALUES
(1, 'mya', false, '2026-05-02 09:00'),
(2, 'promo99', true, '2026-05-03 10:00'),
(3, 'kyaw', false, '2026-05-20 18:30'),
(4, 'promo99', true, '2026-05-28 07:15'),
(5, 'cheap4u', true, '2026-06-03 12:00');
-- TODO 1: preview: how many spam comments are older than 2026-06-01?
-- TODO 2: in a transaction, delete exactly those rows
-- and return comment_id, author
-- TODO 3: list what is left, ordered by comment_idExpected: Preview: 2. The DELETE returns (2, promo99) and (4, promo99) with DELETE 2. Remaining: 1 mya, 3 kyaw, 5 cheap4u.
Show hint
Both conditions must hold, so use AND: is_spam AND created_at < '2026-06-01'. Copy the same WHERE into the preview and the DELETE.
Show solution
SELECT count(*)
FROM comments
WHERE is_spam AND created_at < '2026-06-01';
BEGIN;
DELETE FROM comments
WHERE is_spam AND created_at < '2026-06-01'
RETURNING comment_id, author;
COMMIT;
SELECT comment_id, author, is_spam
FROM comments
ORDER BY comment_id;Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- DELETE FROM ... WHERE removes matching rows; no WHERE means all rows, and there is no undo.
- SELECT preview with the same WHERE, BEGIN, DELETE ... RETURNING, check DELETE n, then COMMIT or ROLLBACK.
- A foreign key blocks deleting a parent that has children; CASCADE removes the children too.
- Use TRUNCATE to empty a whole table and a soft delete (deleted_at) when history matters.
PostgreSQL SQL Tutorial — PostgreSQL Global Development Group