# Topic 9: DELETE Statements
Row deletion mechanics, WHERE safeguards, DELETE RETURNING, cascading constraints, and DELETE vs TRUNCATE differences.
1. Definition
The DELETE statement is a DML command that removes one or more rows from a table based on a predicate, firing triggers and maintaining transactional rollback capability.
2. Explain Like I'm 5
DELETE is like taking an individual piece of paper out of a filing folder and putting it in the shredder. The folder stays, but that specific sheet is gone.
3. Animation & Visual Simulation
Interactive Engine TraceDELETE Statements Visual Simulator
DELETE FROM cart_items
WHERE cart_id = 99
RETURNING id, product_id;Active InputStep 1: Input & Parsing Stage
Initiating DELETE Statements
Checking Table Invariants
The database engine inspects active tables, verifies permissions, and prepares the physical operation.
4. Real-World Example
An application deletes expired session tokens older than 30 days.
| token | user_id | expires_at |
|---|---|---|
| tok_111 | 1 | 2026-01-01 (Expired) |
| tok_222 | 2 | 2026-12-31 (Active) |
5. SQL Syntax
ANSI SQL / PostgreSQL DialectDELETE FROM user_sessions WHERE expires_at < CURRENT_TIMESTAMP;
DELETE FROM orders WHERE status = 'cancelled' AND created_at < NOW() - INTERVAL '90 days' RETURNING id, user_id, total_usd;
6. Important Rules & Behaviors
| Rule | Behavioral Explanation |
|---|---|
| Missing WHERE Clause | DELETE FROM table_name without WHERE deletes all rows in the table row-by-row. |
| Foreign Key Enforcement | If a deleted row is referenced by child tables, deletion fails unless ON DELETE CASCADE or SET NULL is configured. |
| Trigger Activation | DELETE activates BEFORE DELETE and AFTER DELETE triggers for every removed row. |
| Dead tuple creation | DELETE marks row slots dead by setting xmax; space is not reclaimed until VACUUM runs. |
| Cascading lock escalation | Deleting a parent row cascades to child tables, acquiring row-level locks across multiple tables simultaneously. |
7. Deep Dive: DELETE vs TRUNCATE Architecture
DELETE scans rows, checks visibility, acquires row locks, generates full WAL records, and marks tuples dead. TRUNCATE is a DDL command that instantly resets the table file on disk (allocating new empty disk fork), which is orders of magnitude faster.
-- Slow for millions of rows (logged row-by-row): DELETE FROM large_logs; -- Instant (deallocates storage pages directly): TRUNCATE TABLE large_logs;
8. Advantages & Disadvantages
Advantages
- •Precise row targeting via standard WHERE predicates.
- •Supports transactional ROLLBACK if mistakes occur.
- •RETURNING clause captures deleted records for audit archives.
Disadvantages & Trade-offs
- •Deleting millions of rows creates massive WAL generation and table page fragmentation.
9. Common Interview Questions
Q1.Why does executing DELETE FROM users; not free up disk space immediately in PostgreSQL?
Because of Multi-Version Concurrency Control (MVCC). Other concurrent transactions that started before the DELETE may still need to read the old row versions. PostgreSQL simply records the current transaction ID in the tuple header’s xmax field, marking it invisible to future queries. The disk space is only marked reusable when autovacuum runs, and physical file size shrinks only with VACUUM FULL.
Q2.What is Soft Delete and what are its major architectural and performance trade-offs?
Soft Delete adds an is_deleted BOOLEAN or deleted_at TIMESTAMPTZ column instead of physically deleting rows. Advantages: audit recovery and historical compliance. Severe Drawbacks: 1. Every single query must remember to append WHERE deleted_at IS NULL, 2. Unique constraints become complicated (e.g. unique email among active users requires partial indexes), 3. Table and index sizes continuously bloat over time.
Q3.How do you safely delete 10,000,000 rows from a production table without bringing down the database?
Deleting 10 million rows in one statement acquires long-running exclusive locks, explodes the Write-Ahead Log (WAL), stalls replication standby nodes, and risks lock timeouts. The production best practice is batch deletion in small chunks (e.g. 5,000 rows at a time) inside a loop with a small sleep between batches to allow autovacuum and replication to keep up.
DO $$
DECLARE rows_deleted INT;
BEGIN
LOOP
DELETE FROM audit_logs
WHERE id IN (
SELECT id FROM audit_logs
WHERE created_at < NOW() - INTERVAL '90 days'
LIMIT 5000
);
GET DIAGNOSTICS rows_deleted = ROW_COUNT;
EXIT WHEN rows_deleted = 0;
PERFORM pg_sleep(0.05); -- brief throttle for replication
END LOOP;
END $$;Q4.What is the difference between DELETE, TRUNCATE, and DROP TABLE?
DELETE removes rows one by one, writes full WAL logs, and fires triggers. TRUNCATE instantly deallocates entire data pages, resets sequences, requires an AccessExclusiveLock, and does not fire row triggers. DROP TABLE removes the entire table definition, constraints, indexes, and metadata completely from the system catalog.
Q5.What happens when you delete a row with Foreign Key dependencies?
The engine inspects the foreign key constraint definition: ON DELETE RESTRICT (or NO ACTION) immediately aborts the delete with an error if child records exist. ON DELETE CASCADE automatically deletes all referencing child rows. ON DELETE SET NULL sets the referencing child foreign key columns to NULL. If foreign key columns lack indexes, cascading deletes cause full table scans on child tables.
10. Interview-Ready Answer
“The DELETE statement removes filtered rows while logging each change and checking foreign key referential integrity. In high-volume systems, TRUNCATE is preferred for bulk wipes, while soft-deletes (is_deleted = true) are often used to preserve audit history.”
11. Quick Test
Why does TRUNCATE execute significantly faster than DELETE on a 10-million row table?