Explain DELETE in SQL
The DELETE
statement in SQL is used to remove rows from a table. This statement can delete specific rows based on conditions, or it can delete all rows if no condition is specified.
Here are the basic syntaxes:
-
Delete Specific Rows:
DELETE FROM table_name WHERE condition;
-
Delete All Rows:
DELETE FROM table_name;
Examples
Example 1: Delete Specific Rows
Suppose we have a table called employees
:
CREATE TABLE employees (
id INT PRIMARY KEY,
name VARCHAR(50),
position VARCHAR(50),
salary DECIMAL(10, 2)
);
INSERT INTO employees (id, name, position, salary) VALUES
(1, 'Alice', 'Manager', 75000),
(2, 'Bob', 'Developer', 60000),
(3, 'Charlie', 'Designer', 55000),
(4, 'David', 'Developer', 62000);
To delete the employee with the name 'Bob':
DELETE FROM employees
WHERE name = 'Bob';
Result:
The table employees
will now look like this:
id | name | position | salary |
---|---|---|---|
1 | Alice | Manager | 75000 |
3 | Charlie | Designer | 55000 |
4 | David | Developer | 62000 |
Example 2: Delete All Rows
To delete all rows from the employees
table:
DELETE FROM employees;
Result:
The table employees
will now be empty:
id | name | position | salary |
---|
Important Points
- Use with Caution: The
DELETE
statement can be very powerful and potentially dangerous if used incorrectly. Always make sure to specify aWHERE
clause unless you intend to delete all rows. - Transactions: It's good practice to use transactions when performing delete operations to ensure data integrity. You can rollback the transaction if something goes wrong.
- Referential Integrity: Be cautious of foreign key constraints that might affect the deletion of rows. Deleting rows that are referenced by other tables might lead to errors or unexpected behavior.
Example with Transactions
BEGIN TRANSACTION;
DELETE FROM employees
WHERE name = 'Alice';
-- Check if the deletion is as expected
SELECT * FROM employees;
-- If everything looks good
COMMIT;
-- If something went wrong
ROLLBACK;
By using transactions, you can ensure that your delete operation is safe and can be undone if necessary.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.