Learning of SQL Day 10

 

Day 10: DELETE Statement

Introduction:

  • The DELETE statement 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:

  1. Basic DELETE Statement:

    • Remove rows that match a specific condition.

sql
-- Delete the student with StudentID = 1
DELETE FROM Students
WHERE StudentID = 1;
  1. Deleting Multiple Rows:

    • Use conditions to delete multiple rows.

sql
-- Delete all students who are younger than 20
DELETE FROM Students
WHERE Age < 20;
  1. Deleting All Rows:

    • Remove all rows from a table without deleting the table itself.

sql
-- Delete all records from the Students table
DELETE FROM Students;

Practice Exercise:

  1. Use the Employees table created previously with columns EmployeeID, FirstName, LastName, Department, and Salary.

  2. Write a query to delete an employee with EmployeeID = 2.

  3. Write a query to delete all employees from the HR department.

  4. Write a query to delete all employees with a salary less than 50000.

sql
-- 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 WHERE clause 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. 

Post a Comment

0 Comments