In this SQL Server tutorial, you’ll learn how to use OR operator to combine two or more Boolean expressions in a T-SQL query in Microsoft SQL Server along with its syntax and some examples.
What is OR operator in SQL Server?
The OR operator in SQL Server is a logical operator and also known as OR condition that is usually used to combine two of more Boolean expressions. It returns TRUE when even one of the expression returns true.
Following is the syntax of the OR operator in SQL Server.
WHERE expression1 OR expression2 ... OR expressionn;
- expression1, expression2, expressionn
- These are the conditions that must be met for the records to be filtered. Note that even if one of the condition is true, the records will be filtered.
Note : When you use more than one logical operator in a SQL statement. For example AND and OR, Microsoft SQL Server first processes the AND operator and then the OR operator. You can change the order of precedence by using parentheses.
Example 1 : Using OR operator to evaluate two conditions
The below SQL query find all the Person records where the title is Mr. or EmailPromotion is set.
SELECT * FROM [Person].[Person] WHERE Title = 'Mr.' OR EmailPromotion = 1
Example 2 : Using Multiple OR Operators in SQL
The below query returns all the Person records that meets either ONE of the conditions as specified below
- Title = “Mr.”
- EmailPromotion = 1
- PersonType = “SP”
SELECT * FROM [Person].[Person] WHERE Title = 'Mr.' OR EmailPromotion = 1 OR PersonType = 'SP'
Example 3 : Using IN operator instead of OR
When you want to filter the records based on multiple values of the same field, you’ll usually end up using the OR operator. For example, the below query returns all the Person records where the PersonType is either SP or SC.
SELECT * FROM [Person].[Person] WHERE PersonType = 'SP' OR PersonType = 'SC'
You can easily replace multiple OR operators on the same fields in a SQL Query using the IN operator. For example, the below SQL Query exactly returns the same results as the above T-SQL query but using the IN operator.
SELECT * FROM [Person].[Person] WHERE PersonType IN( 'SP','SC')