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.
/* Answer */ SELECT FirstName, LastName FROM Person.Person WHERE FirstName = '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?
/* Answer */ SELECT FirstName, LastName FROM Person.Person WHERE FirstName <> '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.
/* Answer */ SELECT FirstName, LastName FROM Person.Person WHERE FirstName IN ('Terry', '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.
/* Answer */ SELECT FirstName, LastName FROM Person.Person WHERE FirstName IN ('Tom', 'Tomas', 'Tommy') ORDER BY FirstName, LastName
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:
/* Answer */ SELECT FirstName, LastName FROM Person.Person WHERE FirstName NOT IN ('Terry', 'Terri')
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:
/* Answer */ SELECT BusinessEntityID, FirstName, LastName FROM Person.Person WHERE BusinessEntityID BETWEEN 1000 and 1025
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.