SQL DELETE Statement

Here’s a clean and practical guide to the SQL DELETE statement`, including safe-use practices and engine-specific notes.


✅ Basic Syntax

DELETE FROM table_name
WHERE condition;

Always include a WHERE clause unless you truly intend to delete every row.


✅ Delete a Single Row

DELETE FROM users
WHERE id = 5;

✅ Delete Using Multiple Conditions

DELETE FROM orders
WHERE status = 'canceled'
AND created_at < '2024-01-01';

❌ Delete All Rows (use extreme caution)

DELETE FROM logs;

Better for large tables (faster, resets auto-increment):

TRUNCATE TABLE logs;

🔥 Delete with Subquery

DELETE FROM sessions
WHERE user_id IN (
SELECT id FROM users WHERE is_active = 0
);

🔧 Delete with JOIN (engine-specific)

PostgreSQL

DELETE FROM orders o
USING customers c
WHERE o.customer_id = c.id
AND c.status = 'inactive';

MySQL

DELETE o
FROM orders o
JOIN customers c ON o.customer_id = c.id
WHERE c.status = 'inactive';

🔐 Best Practices for Safe Deletes

✔ First run a SELECT with the same WHERE clause
✔ Make sure the table is backed up (or in a transaction)
✔ Use proper indexing on the WHERE columns
✔ For large datasets, delete in batches

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *