SQL AND, OR, NOT

The SQL AND, OR, and NOT Operators

The WHERE clause can be combined with AND, OR, and NOT operators to filter records based on more than one condition.


Syntax

AND Syntax

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

OR Syntax

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

NOT Syntax

SELECT column1, column2, ...
FROM table_name
WHERE NOT condition;

Demo Database

Below is a selection from the Customers table:

Customers Table:

CustomerID CustomerName City Country
1 Alfreds Futterkiste Berlin Germany
2 Ana Trujillo Emparedados México D.F. Mexico
3 Antonio Moreno Taquería México D.F. Mexico
4 Berglunds snabbköp Luleå Sweden

Example 1: Using AND

The following SQL statement selects all customers from the country "Germany" AND has a CustomerID of 1.

AND Example

SELECT * FROM Customers
WHERE Country = 'Germany' AND CustomerID = 1;

Example 2: Using OR

The following SQL statement selects all customers from the country "Germany" OR the country "Sweden".

OR Example

SELECT * FROM Customers
WHERE Country = 'Germany' OR Country = 'Sweden';

Example 3: Using NOT

The following SQL statement selects all customers that are NOT from the country "Germany".

NOT Example

SELECT * FROM Customers
WHERE NOT Country = 'Germany';

Combining AND, OR, and NOT

You can also combine these operators. Use parentheses to form complex expressions and control the order of evaluation.

The following SQL statement selects all customers from "Mexico" that have a CustomerID of 2 OR 3.

Combining Operators Example

SELECT * FROM Customers
WHERE Country = 'Mexico' AND (CustomerID = 2 OR CustomerID = 3);