How to Delete a Single Record from a SQL Table Based on Condition
Delete a Single Record
Write a SQL query to delete a single record from a table based on a specific condition.
Solution:
-- Delete the employee with EmployeeID = 4.
DELETE FROM Employees -- Specify the table to delete from.
WHERE EmployeeID = 4; -- Delete only the employee with ID 4.
Explanation:
- The goal is to delete a specific employee record from the Employees table.
- This demonstrates how to use the DELETE statement to remove a single row from a table based on a condition.
- DELETE FROM Employees : Specifies the table from which the record will be deleted.
- WHERE EmployeeID = 4 : Ensures that only the employee with EmployeeID = 4 is deleted.
- The DELETE statement is used to remove records from a table, making it essential for maintaining clean and accurate data.
- For example, if an employee leaves the company, their record can be removed from the database using this statement.
- For example, in a company database, you might use this query to delete the record of an employee with EmployeeID = 4 who has resigned or been terminated.
1. Purpose of the Query :
2. Key Components :
3. Why use DELETE? :
4. Real-World Application :
Additional Notes:
- “WHERE” clause is critical to ensure that only the intended record is deleted.
- Scenarios where deleting a single record is appropriate, such as:
- Removing outdated or redundant data (e.g., employees who have left the company).
- Correcting erroneous entries in the database.
- Important Considerations :
- Always include a WHERE clause to avoid unintentionally deleting all rows in the table.
- Verify that the condition in the WHERE clause uniquely identifies the target record.
For more Practice: Solve these Related Problems:
- Write a SQL query to delete a single record from the 'customers' table where the deletion condition includes a subquery comparing aggregated values.
- Write a SQL query to delete a single record from a table by joining it with another table to evaluate a complex deletion condition.
- Write a SQL query to delete a single record that meets multiple complex criteria involving date ranges and numeric thresholds.
- Write a SQL query to delete a single record from a table using a LIMIT clause (or its equivalent) to ensure only one record is removed.
- Write a SQL query to delete a single record within a transaction that rolls back the deletion if a secondary condition is not met.
Go to:
PREV : Update Multiple Records.
NEXT : Delete Multiple Records.
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.