In this SQL Server tutorial, you’ll learn how to use both the AND operator and OR operator together in a single SQL Select statement with an example.
Syntax
WHERE expression1 AND expression2 ... OR expressionn;
Parameters
- expression1, expression2, expression3
- These are the conditions that must be met for the records to 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 AND & OR in a SELECT statement in T-SQL
Let’s have a look at an example SQL query that shows how to combine AND and OR operator in a single SELECT statement in SQL Server. The below SQL query return all Person records that is has both Email Promotion of 1 and PersonType = ‘SP’ or if the Title is Mr.
SELECT * FROM [Person].[Person] WHERE Title = 'Mr.' OR EmailPromotion = 1 AND PersonType = 'SP'
Example 2: Using AND & OR with parentheses in a SELECT statement in T-SQL
The previous SQL query can tweaked to include parentheses so that we can control order of precedence in which AND and OR is processed by SQL Server. In the below SQL Query, the records are filtered first by Title=Mr. or EmailPromotion as they both are inside parentheses and then if the PersonType is ‘SP’
SELECT * FROM [Person].[Person] WHERE (Title = 'Mr.' OR EmailPromotion = 1) AND PersonType = 'SP'