How to use the where clause with the delete statement in SQL
Overview
In SQL, the WHERE clause is used alongside the DELETE statement to delete a specified record from a table.
The WHERE clause is commonly used with comparison operators. These include:
=(equal to operator)!=(not equal to operator)>(greater than operator)<(less than operator)>=(greater than or equal to operator)<=(less than or equal to operator)
It is worth noting that:
- If the
WHEREclause has the primary key with the=operator, then only one record can be affected —if they are found. - Similarly, like in the case described above, if the
WHEREclause has the non-primary key with the=operator, then multiple records can be affected —if they are found. - Irrespective of the key type (either primary or non-primary) and with the inequality operators
<or>, multiple records will be affected, if they are found.
Syntax
The syntax of the DELETE statement is given below:
DELETE FROM name_of_table
WHERE condition;
Database schema
The database we will be working with is shown below:
Customers
CustomerID | Name | Country |
1 | Theo David | U.S.A |
2 | Peter Mark | United Kingdom |
3 | Antonio Clark | Mexico |
4 | Benjamin Monday | U.S.A |
Code example
In the code written below, we will use the WHERE clause alongside the DELETE statement to delete a specific part of the Customers table.
-- using the WHERE clause alongside the SELECT statementDELETE FROM CustomersWHERE CustomerName='Benjamin Monday';-- printing the modified tableSELECT * FROM Customers
Code explanation
- We declare the
Customerstable and populate it with values, according to the defined database schema on our platform. - In the statements shown above, we apply the
WHEREclause and theDELETEstatement with a condition of where theCustomerNameisBenjamin Monday. - Then, we print the modified table called
Customers.
Note: Notice from the output of the code that the record which has the
CustomerNameasBenjamin Mondayhas been deleted.