AND, OR, NOT

The SQL AND Operator

AND returns a row only if all conditions are true.

Example

Customers from the UK who live in London:

SELECT * FROM Customers
WHERE Country = 'UK' AND City = 'London';

Result: 2 rows

CustomerIDCustomerNameContactNameCityCountry
2Blue Harbor FoodsEmma ClarkLondonUK
8Harbor LightsOlivia MartinLondonUK

The SQL OR Operator

OR returns a row if any condition is true.

Example

Customers from India or Canada:

SELECT * FROM Customers
WHERE Country = 'India' OR Country = 'Canada';

Result: 3 rows

CustomerIDCustomerNameContactNameCityCountry
1Aarav TradersAarav ShahMumbaiIndia
3Cedar & CoLiam BrownTorontoCanada
4Delta MartPriya NairBengaluruIndia

The NOT Operator

NOT reverses a condition.

Example

Products that are not in the Snacks category:

SELECT ProductName, Category FROM Products
WHERE NOT Category = 'Snacks';

Result: 4 rows

ProductNameCategory
Basmati Rice 5kgGrocery
Green Tea 100 bagsBeverages
Olive Oil 1LGrocery
Espresso Beans 1kgBeverages

NOT combines with other operators: NOT LIKE, NOT BETWEEN, NOT IN, IS NOT NULL.

Combining AND and OR

AND is evaluated before OR. Use parentheses to make the meaning explicit.

Example

Sales employees who earn more than 60000 or were hired before 2020. Without parentheses the result is wrong:

SELECT FirstName, Department, Salary, HireDate FROM Employees
WHERE Department = 'Sales' AND Salary > 60000 OR HireDate < '2020-01-01';

Result: 4 rows

FirstNameDepartmentSalaryHireDate
RahulSales720002019-04-01
DavidSales610002020-11-02
JamesSupport670002018-09-23
FatimaFinance800002017-03-05

Example (correct)

With parentheses, only Sales employees are returned:

SELECT FirstName, Department, Salary, HireDate FROM Employees
WHERE Department = 'Sales' AND (Salary > 60000 OR HireDate < '2020-01-01');

Result: 2 rows

FirstNameDepartmentSalaryHireDate
RahulSales720002019-04-01
DavidSales610002020-11-02

Exercise

Exercise: Select products in the Beverages category that cost less than 10.

Show answer
SELECT * FROM Products
WHERE Category = 'Beverages' AND Price < 10;