🗄️SQL Templates

DELETE Data Patterns

Safely delete records with WHERE conditions and cascading deletes

Explanation

Remove records from database tables with proper safeguards and cascade handling.

Examples

Delete with WHERE
Input
DELETE FROM users WHERE id = 1
Output
Deletes only user with id 1
Delete all (dangerous)
Input
DELETE FROM temp_table
Output
Removes all rows from table

Code Examples

SQL
-- Delete single row
DELETE FROM users 
WHERE id = 1;

-- Delete with multiple conditions
DELETE FROM sessions 
WHERE expired_at < NOW() 
  AND user_id IS NOT NULL;

-- Delete old records
DELETE FROM logs 
WHERE created_at < NOW() - INTERVAL '90 days';

-- Delete with subquery
DELETE FROM users 
WHERE id IN (
  SELECT user_id 
  FROM banned_users
);

-- Delete with JOIN (MySQL)
DELETE u 
FROM users u
INNER JOIN deleted_accounts d ON u.email = d.email;

-- Delete and return (PostgreSQL)
DELETE FROM users 
WHERE id = 1
RETURNING *;

-- Delete all rows (BE CAREFUL!)
DELETE FROM temp_table;

-- Better: TRUNCATE (faster, resets auto-increment)
TRUNCATE TABLE temp_table;

-- Soft delete (recommended over hard delete)
UPDATE users 
SET deleted_at = NOW(), status = 'deleted'
WHERE id = 1;

-- Delete with LIMIT (MySQL - for batch deletes)
DELETE FROM logs 
WHERE created_at < '2023-01-01'
LIMIT 1000;

-- Batch delete loop (MySQL)
WHILE (SELECT COUNT(*) FROM logs WHERE created_at < '2023-01-01') > 0
DO
  DELETE FROM logs 
  WHERE created_at < '2023-01-01'
  LIMIT 1000;
  -- Pause between batches
  SELECT SLEEP(1);
END WHILE;

💡 Tips

  • ALWAYS use WHERE clause (unless deleting all)
  • Test with SELECT COUNT(*) before DELETE
  • Use soft deletes for important data
  • Consider foreign key constraints (CASCADE)
  • Use transactions for related deletes
  • Archive data before deleting
  • Use LIMIT for large batch deletes
  • TRUNCATE is faster than DELETE for all rows

⚠️ Common Pitfalls

  • Forgetting WHERE deletes ALL rows!
  • Foreign key constraints can block deletes
  • CASCADE deletes can remove unexpected data
  • No undo after DELETE (without backup)
  • Large deletes can lock tables
  • TRUNCATE cannot be rolled back in some DBs
  • Deletes are slower than TRUNCATE