Day 10: DELETE Statement
Introduction:
The
DELETEstatement is used to remove existing records from a table. It's an essential command for maintaining and cleaning up your database.
Key Concepts:
Deleting Data: Removing records from a table.
WHERE Clause: Specifies which rows to delete.
SQL Commands and Examples:
Basic DELETE Statement:
Remove rows that match a specific condition.
-- Delete the student with StudentID = 1
DELETE FROM Students
WHERE StudentID = 1;
Deleting Multiple Rows:
Use conditions to delete multiple rows.
-- Delete all students who are younger than 20
DELETE FROM Students
WHERE Age < 20;
Deleting All Rows:
Remove all rows from a table without deleting the table itself.
-- Delete all records from the Students table
DELETE FROM Students;
Practice Exercise:
Use the Employees table created previously with columns
EmployeeID,FirstName,LastName,Department, andSalary.Write a query to delete an employee with
EmployeeID= 2.Write a query to delete all employees from the
HRdepartment.Write a query to delete all employees with a salary less than 50000.
-- Delete the employee with EmployeeID = 2
DELETE FROM Employees
WHERE EmployeeID = 2;
-- Delete all employees from the HR department
DELETE FROM Employees
WHERE Department = 'HR';
-- Delete all employees with a salary less than 50000
DELETE FROM Employees
WHERE Salary < 50000;
Important Tips:
Always use the
WHEREclause to specify which rows to delete; otherwise, all rows in the table will be deleted.Be cautious when deleting data to avoid accidental loss of important records.
Mastering the DELETE statement is crucial for maintaining a clean and organized database.
0 Comments