Careeroza
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
| CustomerID | CustomerName | ContactName | City | Country |
|---|---|---|---|---|
| 2 | Blue Harbor Foods | Emma Clark | London | UK |
| 8 | Harbor Lights | Olivia Martin | London | UK |
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
| CustomerID | CustomerName | ContactName | City | Country |
|---|---|---|---|---|
| 1 | Aarav Traders | Aarav Shah | Mumbai | India |
| 3 | Cedar & Co | Liam Brown | Toronto | Canada |
| 4 | Delta Mart | Priya Nair | Bengaluru | India |
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
| ProductName | Category |
|---|---|
| Basmati Rice 5kg | Grocery |
| Green Tea 100 bags | Beverages |
| Olive Oil 1L | Grocery |
| Espresso Beans 1kg | Beverages |
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
| FirstName | Department | Salary | HireDate |
|---|---|---|---|
| Rahul | Sales | 72000 | 2019-04-01 |
| David | Sales | 61000 | 2020-11-02 |
| James | Support | 67000 | 2018-09-23 |
| Fatima | Finance | 80000 | 2017-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
| FirstName | Department | Salary | HireDate |
|---|---|---|---|
| Rahul | Sales | 72000 | 2019-04-01 |
| David | Sales | 61000 | 2020-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;