SQL Server - AND, OR, & NOT Operators
The SQL Server (Transact-SQL) WHERE clause conditions can be combined using AND, OR, and NOT operators. These operators are used to handle more than one conditions.
- AND - Used to combine multiple conditions and displays a record if all the conditions separated by AND operator are true.
- OR - Used to combine multiple conditions and displays a record if any of the conditions separated by OR operator is true.
- NOT - Used to display a record where the specified condition is not true.
Syntax
The syntax for using these operators in SQL Server (Transact-SQL) are given below:
/* AND Operator */ SELECT column1, column2, column3, ... FROM table_name WHERE condition1 AND condition2 AND condtion3 ....; /* OR Operator */ SELECT column1, column2, column3, ... FROM table_name WHERE condition1 OR condition2 OR condtion3 ....; /* NOT Operator */ SELECT column1, column2, column3, ... FROM table_name WHERE NOT condition;
Example:
Consider a database table called Employee with the following records:
EmpID | Name | City | Age | Salary |
---|---|---|---|---|
1 | John | London | 25 | 3000 |
2 | Marry | New York | 24 | 2750 |
3 | Jo | Paris | 27 | 2800 |
4 | Kim | Amsterdam | 30 | 3100 |
5 | Ramesh | New Delhi | 28 | 3000 |
6 | Huang | Beijing | 28 | 2800 |
-
AND Example: To select all records of the Employee table where Salary is greater than 2800 and Age is less than 30, the query is mentioned below:
SELECT * FROM Employee WHERE Salary > 2800 AND Age < 30;
This result of the following code will be:
EmpID Name City Age Salary 1 John London 25 3000 5 Ramesh New Delhi 28 3000 -
OR Example: To select all records of the Employee table where Salary is greater than 2800 or Age is less than 25, the query is given below.
SELECT * FROM Employee WHERE Salary > 2800 OR Age < 25;
This will produce the result as shown below:
EmpID Name City Age Salary 1 John London 25 3000 2 Marry New York 24 2750 4 Kim Amsterdam 30 3100 5 Ramesh New Delhi 28 3000 -
NOT Example: To select all records of the Employee table where City is NOT "New Delhi", the query is given below.
SELECT * FROM Employee WHERE NOT City = 'New Delhi';
This result of the query is shown below:
EmpID Name City Age Salary 1 John London 25 3000 2 Marry New York 24 2750 3 Jo Paris 27 2800 4 Kim Amsterdam 30 3100 6 Huang Beijing 28 2800