SQL Server Logical Operators

SQL Server - Logical Operators

SQL Server supports logical operators such as OR, AND and NOT.

  • OR : returns the result when any of the condition is true.
  • AND : returns the result when all the condition is true.
  • NOT : returns the result when condition is false.

Logical operators can be used in the WHERE clause.

Logical Operators Syntax

SELECT column_name1[, column_name2, ....]
FROM table_name
WHERE [ NOT ] conditional_expression [ AND | OR ] [ NOT ] conditional_expression 

Employee Table

Let us consider the example 'Employee' database table.

Employee table output

Logical Operators Example

OR Operator on WHERE Statement

Either one condition should be true to return the table row. here either country column value should be 'US' or City should be 'Bangalore'.
SELECT *
FROM Employee
WHERE Country = 'US' OR City = 'Bangalore'
Output:
Logical operators output

AND Operator on WHERE Statement

Both condition should be true to return the table row. here each row column DeptId value should be 1 and Country column value should be 'US'.
SELECT *
FROM Employee
WHERE DeptId=1 AND Country = 'US'
Output:
Logical operators output

NOT Operator on WHERE Statement

Condition should be false to return the table row. Each row Country column value should not be 'US'.
SELECT *
FROM Employee
WHERE NOT Country = 'US'
Output:
Logical operators output

Logical Operators Precedence

If Multiple logical operators are used in single query, processing operation takes place based on precedence of logical operators.

Precedence level of logical operators in an expression is NOT, AND, and OR. precedence of logical operators can be changed using parentheses.

SELECT *
FROM Employee
WHERE (NOT (Country = 'US' AND City = 'Bangalore'))
Arithmetic operators output
SELECT *
FROM Employee
WHERE (NOT (Country = 'US' AND City = 'Bangalore')) AND NOT (Country = 'INDIA')
Output:
Arithmetic operators output



Python installation

Privacy Policy  |  Copyrightcopyright symbol2020 - All Rights Reserved.  |  Contact us   |  Report website issues in Github   |  Facebook page   |  Google+ page

Email Facebook Google LinkedIn Twitter
^