The SQL AND, OR and NOT Operators

The WHERE clause can be combined with AND, OR, and NOT operators.

The AND and OR operators are used to filter records based on more than one condition:

  • The AND operator displays a record if all the conditions separated by AND are TRUE.
  • The OR operator displays a record if any of the conditions separated by OR is TRUE.

The NOT operator displays a record if the condition(s) is NOT TRUE.

AND Syntax

SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND condition2 AND condition3 ...;

The AND Operator

The AND operator is a logical operator that combines two conditions and returns TRUE only if both condition evaluate to TRUE . The AND operator is often used in the WHERE clause of the SELECT, UPDATE, DELETE statement to form conditions to filter the result set.

SELECT column1_name, column2_name, columnN_name
FROM table_name
WHERE condition1 AND condition2;

Using WHERE Clause with AND Operator

The following SQL statement will return only those employees from the employees table whose salary is greater than 7000 and the dept_id is equal to 5.

SELECT * FROM employees
WHERE salary > 7000 AND dept_id = 5;

The OR Operator

Similarly, the OR operator is also a logical operator that combines two conditions, but it returns TRUE when either of the conditions is TRUE.

The following SQL statement will return all the employees from the employees table whose salary is either greater than 7000 or the dept_id is equal to 5.

SELECT * FROM employees
WHERE salary > 7000 OR dept_id = 5;

Combining AND & OR Operator

You can also combine AND and OR to create complex conditional expressions.

The following SQL statement will return all the employees whose salary is greater than 5000 and the dept_id is either equal to 1 or 5.

SELECT * FROM employees
WHERE salary > 5000 AND (dept_id = 1 OR dept_id = 5);