SQL Where
The WHERE clause is used to filter records in a database.
It ensures that your query only extracts or modifies rows that meet a specific condition.
Without a WHERE clause, actions like SELECT will pull the entire table, and actions like UPDATE or DELETE will alter every single row.
Basic Syntax
The WHERE clause always comes immediately after the FROM table declaration.
SELECT column1, column2
FROM table_name
WHERE condition;
Real-World Examples:
- Filtering Numbers: Pulling employees who earn a high salary.
SELECT first_name, salary FROM employees
WHERE salary > 70000;
- Filtering Text: Pulling employees in a specific department. Text values must be wrapped in single quotes (
').
SELECT first_name, department FROM employees
WHERE department = 'Marketing';
Common Comparison Operators
You can use a variety of mathematical and logical operators inside your WHERE condition:
| Operator | Meaning | Example |
|---|---|---|
| = | Equal to | WHERE role = 'Manager' |
| != or <> | Not equal to | WHERE status != 'Active' |
| > / < | Greater than / Less than | WHERE age > 21 |
| >= / <= | Greater than or equal / Less than or equal | WHERE price <= 19.99 |
| BETWEEN | Within an inclusive range | WHERE hire_date BETWEEN '2026-01-01' AND '2026-12-31' |
| IN | Matches any value in a specified list | WHERE country IN ('India', 'UK', 'USA') |
| LIKE | Searches for a pattern (uses % as a wildcard) | WHERE email LIKE '%@gmail.com' |
| IS NULL | Checks for empty or missing data | WHERE phone_number IS NULL |
Combining Multiple Conditions (AND, OR, NOT)
To filter by more than one rule at a time, chain your conditions together using logical operators.
Using AND (Both conditions must be true)
-- Finds active employees who work strictly in Sales
SELECT * FROM employees
WHERE department = 'Sales' AND status = 'Active';
Using OR (At least one condition must be true)
-- Finds employees who are either in IT or HR
SELECT * FROM employees
WHERE department = 'IT' OR department = 'HR';
Using NOT (Reverses the condition)
-- Finds employees who do NOT work in the Finance department
SELECT * FROM employees
WHERE NOT department = 'Finance';