The DELETE
statement in SQL is used to remove rows from a table based on a certain condition.
Syntax:
DELETE FROM table_name WHERE condition;
Important Points:
Safety First: Always backup your data before performing
DELETE
operations, especially on production data.Use WHERE Clause Carefully: Without the
WHERE
clause, all rows in the table will be deleted!Performance Consideration: If you are deleting many rows, it may be more efficient to create a new table with only the rows you want to keep, then rename the table.
Example: To delete all employees with the first name 'John' from an employees
table:
DELETE FROM employees WHERE first_name = 'John';
Workshop Exercise:
Setup:
Let's assume you have a table named students
with the following data:
student_id | name | age | grade |
1 | Alice | 18 | A |
2 | Bob | 19 | B |
3 | Charlie | 20 | C |
4 | David | 21 | D |
Exercise Tasks:
Basic Deletion:
Delete the record of the student with the name "Charlie".
After this operation, confirm that "Charlie" is no longer in the table.
Condition Deletion:
Delete all students who have a grade less than 'C'.
Confirm that only students with grades 'A' and 'B' remain in the table.
Full Deletion (CAUTION!):
Delete all records from the students table.
Confirm that the table is now empty.
Solutions:
Basic Deletion:
DELETE FROM students WHERE name = 'Charlie';
Condition Deletion:
DELETE FROM students WHERE grade > 'B';
Full Deletion:
DELETE FROM students;
After each task, participants can use the SELECT
statement to view the table's contents and confirm their results:
SELECT * FROM students;
This exercise should give a practical understanding of how the DELETE
statement works and the importance of using it with caution.