Retrieving Records That Match One or More Conditions
Logical operators are used in the SELECT statement to retrieve records based on one or more conditions. While querying data, you can combine more than one logical operator to apply multiple search conditions. In a SELECT statement, the conditions specified in the WHERE clause are connected by using the logical operators.
The syntax for using logical operators in the SELECT statement is:
SELECT column_list FROM table_name WHERE conditional_expression1 {AND/OR} [NOT] conditional_expression2 where, conditional_expression1 and conditional_expression2 are any conditional expressions.
The three types of logical operators are:
OR :
Returns a true value when at least one condition is satisfied. For example, the following SQL query retrieves records from the Department table when the GroupName is either Manufacturing or Quality Assurance: SELECT * FROM HumanResources.Department WHERE GroupName = ‘Manufacturing’ OR GroupName = ‘Quality Assurance’
AND :
Is used to join two conditions and returns a true value when both the conditions are satisfied. To view the details of all the employees of AdventureWorks who are married and working as a Production Technician
-
WC60, you can use the AND logical operator, as shown in the following query: SELECT * FROM HumanResources.Employee WHERE Title = ‘Production Technician - WC60’ AND MaritalStatus = ‘M’
NOT :
Reverses the result of the search condition. The following SQL query retrieves records from the Department table when the GroupName is not Quality Assurance: SELECT * FROM HumanResources.Department WHERE NOT GroupName = ‘Quality Assurance’ The preceding query retrieves all the rows except the rows that match the condition specified after the NOT conditional expression.