w3resource

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:

    1. Purpose of the Query :

    1. The goal is to delete a specific employee record from the Employees table.
    2. This demonstrates how to use the DELETE statement to remove a single row from a table based on a condition.

    2. Key Components :

    1. DELETE FROM Employees : Specifies the table from which the record will be deleted.
    2. WHERE EmployeeID = 4 : Ensures that only the employee with EmployeeID = 4 is deleted.

    3. Why use DELETE? :

    1. The DELETE statement is used to remove records from a table, making it essential for maintaining clean and accurate data.
    2. For example, if an employee leaves the company, their record can be removed from the database using this statement.

    4. Real-World Application :

    1. 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.

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.



Follow us on Facebook and Twitter for latest update.