Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Performance & internals
Stage 5: Specialization

Part 11 / Topic 3 of 7

DELETE, DELETE USING, and TRUNCATE

DELETE FROM t WHERE ... removes rows; without WHERE it removes all of them, instantly, no confirmation. The second habit exists for exactly this class of statement: wrap risky writes in a transaction —

BEGIN;
DELETE FROM events;
SELECT count(*) AS events_left FROM events;
ROLLBACK;
SELECT count(*) AS events_after_rollback FROM events;
BEGIN
DELETE 7
 events_left 
-------------
           0
(1 row)

ROLLBACK
 events_after_rollback 
-----------------------
                     7
(1 row)

Inside the transaction the table really was empty; ROLLBACK un-happened it. Run the statement, inspect, then COMMIT or ROLLBACK — one slip costs a rollback instead of a career. (Transactions get their full lesson next part; this is the habit-sized dose.)

DELETE ... USING is DELETE's version of UPDATE's FROM — delete events belonging to customers who never completed an order:

BEGIN;
DELETE FROM events AS e
USING customers AS c
WHERE c.customer_id = e.customer_id
  AND NOT EXISTS (SELECT 1 FROM orders o
                  WHERE o.customer_id = c.customer_id
                    AND o.status = 'delivered')
RETURNING e.event_id, e.event_type, c.first_name;
ROLLBACK;
BEGIN
 event_id | event_type | first_name 
----------+------------+------------
        6 | view       | Vikram
        7 | cart       | Vikram
(2 rows)

DELETE 2
ROLLBACK

TRUNCATE empties a table without visiting rows — near-instant at any size, the honest tool for wiping test data. The trade-offs: it takes the strongest lock, fires no per-row DELETE triggers, and all-or-nothing is the only setting. To empty everything, TRUNCATE; to remove some rows, DELETE.

🧪 Quick quiz — answer from memory, then check.

  1. The two habits before a risky UPDATE/DELETE?
  2. Why is TRUNCATE faster than unqualified DELETE?
Show the answers
  1. Pre-flight the WHERE as a SELECT; run the write inside BEGIN, inspect, then COMMIT or ROLLBACK.
  2. It deallocates the table's storage instead of deleting row by row.

Exercise 3: Local sourcing flags

What to do: Add a sourcing column to products, then set it to 'local' for every product whose supplier is in India — the supplier table decides, in one UPDATE.

💡 Hint: UPDATE products p SET ... FROM suppliers s WHERE s.supplier_id = p.supplier_id AND s.country = 'India' RETURNING ... — six products, all TechSource's.


Show the solution to Exercise 3
-- Exercise 3: Local sourcing flags (UPDATE ... FROM)
ALTER TABLE products ADD COLUMN IF NOT EXISTS sourcing text;
UPDATE products AS p
SET sourcing = 'local'
FROM suppliers AS s
WHERE s.supplier_id = p.supplier_id
  AND s.country = 'India'
RETURNING p.name, p.sourcing;

Search the guide