SQL WHERE Clause
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'
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 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.