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.
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous SQL Exercise: Update Multiple Records
Next SQL Exercise: Delete Multiplele Records.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics