Use the SQL WHERE Clause filter the rows returned your SELECT statement. The where clause tests each row against one or more conditions. When the conditions return TRUE, the row is included in the result.
SQL Where Clause
Here is an example where get all people whose first name is Terry.
When you use the equals sign (=) it’s called using a comparison operator. As mentioned above, when the comparison is true, then the row is included in the result.
We can also use the not equals comparison operator (<>) to find all persons whose name is not Terry. Can you write the query to find every person not named Terry?
SQL WHERE and IN
Here is another example using the IN operator. Notice the result includes all people whose people first name is either Terry or Terri.
Why don’t you try it now? Try writing a query to select all people having the first name of either Tom, Tomas, or Tomy. Sort the result by First and Last Name.
You can also use NOT IN in you SQL WHERE clause. It does the opposite of IN. If we want to find every person whose name isn’t Terry or Terri, we can write our SQL WHERE like so:
In this case, TRUE is returned with FirstName is not Terry or Terri. The end result is a query returning all rows not include Terry or Terri.
SQL WHERE and BETWEEN
You can also use the BETWEEN operator in a SQL WHERE clause to compare values within a range. In this example we’re finding people whose ID’s are from 1000 to 1025:
Additional Resources
If you’re looking to learn more about using the WHERE clause, then I would recommend these resources:
- Good introductory article on the WHERE clause: How to Filter Your Query Results
- What’s the Difference between WHERE and HAVING clauses?
- Looking for a super SQL book? Check out SQL Queries for Mere Mortals.