Curriculum
In this tutorial, you’ll learn how to filter rows using the WHERE clause in SQL Server’s T-SQL statement.
When you use the “SELECT” statement in SQL Server to query the results, you’ll get all the rows from the table by default. Sometimes, you might not need all the records but a filtered row based on some conditions. The WHERE clause in SQL Server does that for us. WHERE clause can be used with other types of queries apart from SELECT clauses, including UPDATE, DELETE and INSERT clauses.
SELECT columns... FROM TABLENAME WHERE searchcondition;
Let’s see some examples of the WHERE clause with the select statement. We will be using the Person.Person table from the AdventureWorks database for the demo.
The below SQL statement retrieves all the People record from the Person table which contains the EmailPromotions of 1
SELECT * FROM [Person].[Person] WHERE EmailPromotion = 1
In the above SQL query, the WHERE clause will only return the results of the records that has EmailPromotion =1. Since, we have used the * in the SELECT statement, all the fields from the Person table will be returned along with the filtered records.
The below T-SQL query will return records from the Person table that matches two conditions EmailPromotion=1 and PersonType = ‘EM’. The logical operator “AND” is used in the filter and hence only when both the conditions are met, the records will be returned.
SELECT * FROM [AdventureWorks2019].[Person].[Person] WHERE EmailPromotion=1 and PersonType = 'EM'
The below T-SQL query will return records from the Person table that matches two conditions EmailPromotion=1 and PersonType = ‘EM’. The logical operator “OR” is used in the filter and hence even if one of the condition is met, the records will be returned.
SELECT * FROM [Person].[Person] WHERE EmailPromotion=1 OR PersonType = 'EM'
The below T-SQL query will return all records from the Person table that has a BusinessEntity of greater than or equals to 750. The greater than or equals to is one of the examples for comparison operator.
SELECT * FROM [Person].[Person] WHERE BusinessEntityID >= 750
The below T-SQL query uses the IN operator to find Person whose BusinessEntityId is 1 or 3 or 5.
SELECT * FROM [Person].[Person] WHERE BusinessEntityID IN (1,3,5)
The below T-SQL query returns all the PERSON records whose BusinessEntityId is between 1 to 5.
SELECT * FROM [Person].[Person] WHERE BusinessEntityID BETWEEN 1 AND 5
The below T-SQL query returns all the Person records whose FirstName contains Ken.
SELECT * FROM [Person].[Person] WHERE FirstName LIKE '%Ken%'
The below T-SQL query joins two tables that are connected and returns the Person and BusinessEntityContact records that has an Person Id of 291.
SELECT * FROM [Person].[Person] AS PER INNER JOIN Person.BusinessEntityContact AS ADDR on ADDR.PersonID = per.BusinessEntityID WHERE PER.BusinessEntityID = 291