Skip to content
Back to 50 Concepts
Topic 9 of 50foundationsBeginner

# 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.

Relational Invariant:Deterministic relational algebra contract evaluated by the Cost-Based Optimizer.

2. Explain Like I'm 5

Intuitive mental model for beginners

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 Trace
Interactive Engine Simulation

DELETE Statements Visual Simulator

Step 1 of 3
SQL>DELETE FROM cart_items WHERE cart_id = 99 RETURNING id, product_id;Active Input

Step 1: Input & Parsing Stage

Engine Action: Validate SQL syntax and resolve schema metadata for DELETE Statements
SQL Input

Initiating DELETE Statements

Schema Catalog

Checking Table Invariants

How the Database Executes This:

The database engine inspects active tables, verifies permissions, and prepares the physical operation.

💡 Shredding documents: DELETE shreds individual sheets of paper one by one; TRUNCATE empties the entire recycling bin in a single dump.

4. Real-World Example

An application deletes expired session tokens older than 30 days.

User Sessions
tokenuser_idexpires_at
tok_11112026-01-01 (Expired)
tok_22222026-12-31 (Active)
Relational walkthrough: DELETE removes tok_111 while keeping tok_222 intact.

5. SQL Syntax

ANSI SQL / PostgreSQL Dialect
Step 1: Targeted DELETE with WHERE
DELETE FROM user_sessions
WHERE expires_at < CURRENT_TIMESTAMP;
Only expired sessions are targeted.
Step 2: DELETE with RETURNING
DELETE FROM orders
WHERE status = 'cancelled' AND created_at < NOW() - INTERVAL '90 days'
RETURNING id, user_id, total_usd;
Allows the application to log deleted records to an external archive.

6. Important Rules & Behaviors

RuleBehavioral Explanation
Missing WHERE ClauseDELETE FROM table_name without WHERE deletes all rows in the table row-by-row.
Foreign Key EnforcementIf a deleted row is referenced by child tables, deletion fails unless ON DELETE CASCADE or SET NULL is configured.
Trigger ActivationDELETE activates BEFORE DELETE and AFTER DELETE triggers for every removed row.
Dead tuple creationDELETE marks row slots dead by setting xmax; space is not reclaimed until VACUUM runs.
Cascading lock escalationDeleting 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;
Caution: TRUNCATE cannot be filtered with a WHERE clause; it always empties the entire table.

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

Scenario Question:

Why does TRUNCATE execute significantly faster than DELETE on a 10-million row table?

Select your answer: