0
0
SQLquery~5 mins

Why DELETE needs caution in SQL

Choose your learning style9 modes available
Introduction

DELETE removes data from a table permanently. It needs caution because once data is deleted, it can be hard or impossible to get it back.

When you want to remove old or incorrect records from a database.
When cleaning up test data after trying out new features.
When deleting user accounts upon request.
When removing duplicate entries to keep data clean.
When clearing out temporary data that is no longer needed.
Syntax
SQL
DELETE FROM table_name WHERE condition;

The WHERE clause is very important to specify which rows to delete.

If you omit WHERE, all rows in the table will be deleted.

Examples
This deletes the employee with ID 5 only.
SQL
DELETE FROM employees WHERE employee_id = 5;
This deletes all orders before January 1, 2023.
SQL
DELETE FROM orders WHERE order_date < '2023-01-01';
This deletes all rows in the customers table. Use with extreme caution!
SQL
DELETE FROM customers;
Sample Program

This example creates a table, inserts three fruits, deletes the fruit with id 2, then shows the remaining fruits.

SQL
CREATE TABLE fruits (id INT, name VARCHAR(20));
INSERT INTO fruits VALUES (1, 'Apple'), (2, 'Banana'), (3, 'Cherry');
DELETE FROM fruits WHERE id = 2;
SELECT * FROM fruits;
OutputSuccess
Important Notes

Always double-check your WHERE clause before running DELETE.

Consider running a SELECT with the same condition first to see which rows will be deleted.

Back up important data before deleting.

Summary

DELETE removes rows permanently from a table.

Without a WHERE clause, all rows are deleted.

Use DELETE carefully to avoid losing important data.