DELETE, TRUNCATE & Soft Deletes
DELETE
DELETE FROM table_name WHERE condition;
- ⚠️ Without
WHERE, all rows are deleted - Same safety habits as UPDATE: SELECT first, use a transaction, check the count,
RETURNING * - Delete using another table:
DELETE FROM expenses e USING users u WHERE u.id = e.user_id AND u.email = '…' - Delete with a subquery:
WHERE user_id IN (SELECT id FROM users WHERE …)
Foreign keys and DELETE
- If child rows reference the row, the delete is blocked (default), cascaded (
ON DELETE CASCADE) or the link is cleared (ON DELETE SET NULL) — depending on how the FK was defined - In our practice DB, deleting a user cascades to their expenses, accounts and bills
DELETE vs TRUNCATE vs DROP
DELETE– selected rows, row by row, fires triggers, can use WHERETRUNCATE– all rows instantly, can reset identity, no WHEREDROP– removes the table itself
Soft deletes 🛟
Instead of removing the row, mark it as deleted:
- Add
deleted_at TIMESTAMPTZ(NULL = not deleted) - "Delete":
UPDATE … SET deleted_at = now() - Queries add
WHERE deleted_at IS NULL(often hidden in a view) - Restore:
SET deleted_at = NULL
Pros
Undo/recycle bin, audit history, keep related data intact
Cons
Every query must remember the filter; data keeps growing; unique constraints need care; laws like GDPR may require real deletion of personal data
Archiving
Move old rows to an archive table in one statement:
WITH moved AS (DELETE FROM … RETURNING *) INSERT INTO archive SELECT * FROM moved;
Example
-- Preview, then delete inside a transaction
SELECT id, title, amount FROM expenses WHERE amount < 500;
BEGIN;
DELETE FROM expenses
WHERE amount < 500
RETURNING id, title, amount; -- shows exactly what was removed
ROLLBACK; -- (keeping our practice data)
-- Delete using another table
BEGIN;
DELETE FROM bills b
USING users u
WHERE u.id = b.user_id AND u.city = 'Pokhara'; -- DELETE 1 (Ravi's rent)
ROLLBACK;
-- ON DELETE CASCADE: deleting a user removes their expenses too
BEGIN;
SELECT count(*) FROM expenses WHERE user_id = 4; -- 6
DELETE FROM users WHERE id = 4;
SELECT count(*) FROM expenses WHERE user_id = 4; -- 0
ROLLBACK;
-- Soft delete pattern
ALTER TABLE expenses ADD COLUMN deleted_at TIMESTAMPTZ;
UPDATE expenses SET deleted_at = now() WHERE title = 'Movie tickets'; -- "delete"
SELECT count(*) FROM expenses WHERE deleted_at IS NULL; -- 30 visible
UPDATE expenses SET deleted_at = NULL WHERE title = 'Movie tickets'; -- restore ♻️
-- Archive old rows in one statement (move = delete + insert)
CREATE TABLE expenses_archive (LIKE expenses);
WITH moved AS (
DELETE FROM expenses WHERE spent_on < '2026-10-01' RETURNING *
)
INSERT INTO expenses_archive SELECT * FROM moved;
SELECT count(*) FROM expenses_archive; -- 11 September expenses moved