Deleting data in SQL is common but risky. One mistake and you could drop all rows in a table. This guide provides a practical reference for using DELETE
safely.
SQL DELETE Quick Reference
Basic syntax
DELETE FROM table_name WHERE condition;
Omitting WHERE
deletes everything.
Return deleted rows (PostgreSQL)
DELETE FROM users WHERE active = false RETURNING *;
Examples
Delete inactive users:
DELETE FROM users WHERE last_login < NOW() - INTERVAL '6 months';
Delete rows with NULL values:
DELETE FROM items WHERE description IS NULL;
Best Practices
- Always use
WHERE
. - Test with
SELECT
before deleting. -
Use transactions for large deletes:
BEGIN; DELETE FROM logs WHERE created_at < '2024-01-01'; COMMIT;
Backup production data.
Be cautious with cascading deletes.
FAQ
Delete all rows?
DELETE FROM table_name;
Can DELETE affect multiple tables?
No. Use multiple statements or foreign key cascades.
Safe way to test?
SELECT * FROM table_name WHERE condition;
Conclusion
SQL DELETE
is powerful but demands caution. Use WHERE filters, transactions, and backups to protect your data. For more advanced examples and edge cases, read the article The SQL DELETE Statement Explained for more insights.
Top comments (0)