Geek Slack

Getting Started with SQL Server
About Lesson


SQL DELETE Statement


SQL DELETE Statement

The DELETE statement is used to delete existing records in a table.

Basic Syntax:

DELETE FROM table_name
WHERE condition;

Example 1: Deleting a Single Record

DELETE FROM employees
WHERE employee_id = 101;

This query deletes the record of the employee with employee_id 101.

Example 2: Deleting Multiple Records

DELETE FROM employees
WHERE department = 'Sales';

This query deletes all records of employees who belong to the ‘Sales’ department.

Example 3: Deleting All Records

DELETE FROM employees;

This query deletes all records in the “employees” table. Note: Use this with caution as it will remove all data from the table.

Example 4: Deleting Records with JOIN

DELETE e
FROM employees e
JOIN departments d ON e.department_id = d.department_id
WHERE d.department_name = 'HR';

This query deletes all employee records where the department name is ‘HR’ by joining the employees and departments tables.

Example 5: Using Subqueries in DELETE

DELETE FROM employees
WHERE department_id IN (SELECT department_id FROM departments WHERE location = 'New York');

This query deletes all employee records where the department is located in ‘New York’ by using a subquery.

Important Considerations:

  • Always use the WHERE clause to specify which records should be deleted. Omitting the WHERE clause will result in all records in the table being deleted.
  • Back up your data before performing delete operations to prevent accidental data loss.

The DELETE statement is a crucial tool for managing data in your database. Proper usage ensures that unwanted records are removed without affecting the integrity of your data.

Join the conversation