Deleting Data with SQL DELETE

In SQL, the DELETE statement is used to remove data from a table. Deleting data is a crucial aspect of database management, especially when maintaining clean, up-to-date, and accurate datasets. Whether you need to remove outdated records, erroneous entries, or even large sets of data based on specific conditions, the DELETE command allows you to do so efficiently.

In this chapter, we will explore the DELETE statement from its basic syntax to advanced use cases. We’ll cover important topics such as conditional deletion, deleting all rows, cascading deletes, and best practices to avoid common pitfalls.

Basic Syntax of SQL DELETE

The basic structure of the DELETE statement is as follows:

				
					DELETE FROM table_name
WHERE condition;

				
			
  • table_name: The table from which you want to delete data.
  • WHERE: This clause specifies which rows should be deleted. Without a WHERE clause, all rows in the table will be deleted, which can be dangerous if done unintentionally.

Example 1: Deleting a Single Row

Consider the following table, employees:

IDNameDepartmentSalary
1John DoeHR5000
2Jane SmithIT6000
3David GreenSales5500

Let’s say we want to delete the record of John Doe.

Query:

				
					DELETE FROM employees
WHERE id = 1;

				
			

Output (after running the query):

IDNameDepartmentSalary
2Jane SmithIT6000
3David GreenSales5500

Only John Doe’s record (where id = 1) has been deleted.

Deleting Multiple Rows

You can delete multiple rows by modifying the WHERE clause to match multiple records. This is useful when you want to delete all records that meet a certain condition.

Example 2: Deleting Multiple Rows Based on a Condition

Let’s delete all employees from the Sales department.

Query:

				
					DELETE FROM employees
WHERE department = 'Sales';

				
			

Output:

IDNameDepartmentSalary
2Jane SmithIT6000

All employees from the Sales department have been deleted.

Deleting All Rows from a Table

If you want to delete all rows from a table but keep the table structure intact, you can omit the WHERE clause. However, this should be done with caution, as it permanently removes all data in the table.

Example 3: Deleting All Rows (Dangerous Operation)

Query:

				
					DELETE FROM employees;

				
			

Output:

IDNameDepartmentSalary
(empty)

All rows from the employees table are deleted. The table still exists, but it contains no data.

Note: If you mistakenly run this command, there is no way to recover the data unless you have a backup. Always use this type of operation with extreme caution.

Deleting Rows Using AND/OR Conditions

The WHERE clause allows you to combine multiple conditions using the AND and OR operators, giving you fine control over which rows to delete.

Example 4: Using AND in DELETE Statement

Let’s delete all employees in the HR department who earn more than 5000.

Query:

				
					DELETE FROM employees
WHERE department = 'HR' AND salary > 5000;

				
			

Output:

IDNameDepartmentSalary
2Jane SmithIT6000
3David GreenSales5500

No rows were deleted because no one in the HR department meets the condition (salary > 5000).

Example 5: Using OR in DELETE Statement

Let’s delete employees who are either in the HR department or have a salary greater than 6000.

Query:

				
					DELETE FROM employees
WHERE department = 'HR' OR salary > 6000;

				
			

Output:

IDNameDepartmentSalary
3David GreenSales5500

Jane Smith, who works in the IT department and has a salary of 6000, was deleted because her salary met the condition of being greater than 6000.

DELETE vs. TRUNCATE

Both DELETE and TRUNCATE are used to remove data from a table, but there are significant differences between the two.

DELETE

  • Removes specific rows based on a condition.
  • Can be rolled back in a transaction.
  • Slower because each row deletion is logged individually.
  • Does not reset auto-increment counters.

TRUNCATE

  • Removes all rows from a table without a WHERE clause.
  • Cannot be rolled back in most databases (like MySQL).
  • Faster because it doesn’t log each row individually.
  • Resets auto-increment counters in most databases.

TRUNCATE Example:

				
					TRUNCATE TABLE employees;

				
			

This query will remove all rows from the employees table but is faster than DELETE and will reset any auto-increment counters.

Deleting Data with JOIN (DELETE with JOIN)

Sometimes you need to delete rows from a table based on data from another table. In such cases, you can use the JOIN clause in your DELETE statement.

Example 6: DELETE with JOIN

Consider another table, departments, that stores department information:

Department IDDepartment Name
1HR
2IT
3Sales

We want to delete all employees who work in a department that has been removed from the departments table.

Query:

				
					DELETE e
FROM employees e
LEFT JOIN departments d ON e.department = d.department_name
WHERE d.department_name IS NULL;

				
			

Explanation:

  • The query deletes any employee from the employees table where the department is no longer present in the departments table.

Using Subqueries in DELETE Statements

Subqueries can be used within the DELETE statement to define which rows should be deleted based on the results of a subquery.

Example 7: DELETE Using a Subquery

Let’s assume we have another table, performance_reviews, that tracks employee performance:

Employee IDRating
13.0
24.5
32.5

We want to delete all employees who have a performance rating below 3.0.

Query:

				
					DELETE FROM employees
WHERE id IN (SELECT employee_id FROM performance_reviews WHERE rating < 3.0);

				
			

Output:

IDNameDepartmentSalary
2Jane SmithIT6000

The employee with a performance rating below 3.0 (John Doe) was deleted.

Preventing Accidental Deletions

When using the DELETE command, it’s easy to accidentally delete more rows than intended. To avoid this, follow these best practices:

Test Your WHERE Clause with a SELECT Statement

  • Before running a DELETE query, run a SELECT query with the same WHERE clause to verify which rows will be affected.

				
					SELECT * FROM employees WHERE department = 'Sales';

				
			

Use Transactions for Large or Critical Deletions

  • For critical deletions, use transactions. This way, if something goes wrong, you can roll back the changes.

				
					START TRANSACTION;
DELETE FROM employees WHERE department = 'Sales';
COMMIT;

				
			

Always Backup Your Data

  • Before running mass deletions, ensure you have a recent backup of the table or database, especially in production environments.

Avoid Omitting the WHERE Clause

  • Never run a DELETE query without the WHERE clause unless you are absolutely sure that you want to delete all rows.

Best Practices for Using SQL DELETE

Limit the Number of Rows Deleted

  • If you need to delete a large number of rows, consider deleting in smaller batches to avoid locking issues or performance degradation.

				
					DELETE FROM employees WHERE department = 'Sales' LIMIT 100;

				
			

Use Foreign Key Constraints with ON DELETE CASCADE

  • If your tables are related via foreign keys, consider using the ON DELETE CASCADE option when creating foreign

key constraints. This ensures that related rows in other tables are automatically deleted when the primary row is deleted.

The DELETE statement in SQL is a powerful tool for removing data from tables. From simple deletions based on conditions to more advanced scenarios like using subqueries or joins, the flexibility of DELETE allows for efficient data management. Happy coding !❤️

Table of Contents

Contact here

Copyright © 2025 Diginode

Made with ❤️ in India