Sub topic 5
Keeping only matching rows with WHERE
The WHERE clause filters rows. Without it, a query returns every row in the table. With it, the database returns only the rows for which a condition holds. This chapter covers how WHERE evaluates, where it sits in a query, and the mistakes that cause empty or surprising results.
This chapter assumes you can write a basic SELECT ... FROM query and know what tables, rows, and columns are. Later chapters cover the individual operators in detail, so here we use only simple conditions.
Sample data
The examples use this table. The statements run as written on PostgreSQL, MySQL, and SQLite.
CREATE TABLE employees (
employee_id INTEGER PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
department VARCHAR(50),
salary INTEGER,
hire_date DATE,
manager_id INTEGER
);
INSERT INTO employees VALUES
(1, 'Ana', 'Silva', 'Sales', 52000, '2019-03-11', NULL),
(2, 'Ben', 'McCoy', 'Sales', 47000, '2021-06-01', 1),
(3, 'Chloe', 'Park', 'Marketing', 58000, '2020-09-15', 1),
(4, 'Dev', 'Rao', 'Support', 39000, '2022-01-20', 3),
(5, 'Eli', 'Stone', 'Sales', 61000, '2018-05-07', 1),
(6, 'Fay', 'Kim', 'Marketing', 45000, '2023-02-13', 3),
(7, 'Gus', 'Lopez', NULL, 41000, '2022-08-30', 3);Gus has no department on record. That NULL matters later in this chapter.
The working model: a per-row test
WHERE takes a condition, called a predicate, and tests it against each row of the table named in FROM. A predicate has one of three outcomes for a row:
- TRUE: the row stays.
- FALSE: the row is discarded.
- UNKNOWN: the row is discarded. This happens when the test involves a
NULL.
Only TRUE keeps a row. This one rule explains most WHERE surprises.
SELECT first_name, department
FROM employees
WHERE department = 'Sales';| first_name | department |
|---|---|
| Ana | Sales |
| Ben | Sales |
| Eli | Sales |
The database checks department = 'Sales' for all seven rows and keeps the three where the result is TRUE.
Where WHERE goes
The clause order is fixed: SELECT, FROM, WHERE, then ORDER BY. Putting WHERE after ORDER BY is a syntax error.
SELECT first_name, salary
FROM employees
WHERE salary > 50000
ORDER BY salary DESC;The query returns Eli (61000), Chloe (58000), and Ana (52000).
The filter does not have to use columns you select. This query returns names, yet it filters on salary and department, which are not in the output:
SELECT first_name, last_name
FROM employees
WHERE salary > 50000
AND department = 'Sales';This returns Ana and Eli.
Literals, quotes, and case
SQL writes text values in single quotes: 'Sales'. Numbers take no quotes. Dates are normally written as quoted text in YYYY-MM-DD form, such as '2021-06-01'.
Double quotes mean something different. In standard SQL, and in PostgreSQL and SQLite, "Sales" is an identifier, a name of a column or table. So WHERE department = "Sales" looks for a column named Sales. PostgreSQL then raises an error. SQLite, for compatibility, falls back to treating it as a string, which hides the mistake. MySQL accepts double quotes as strings by default. Use single quotes for text values everywhere.
Case sensitivity of text comparison depends on the database and the column's collation, which is the rule set for comparing and ordering text:
- PostgreSQL and SQLite compare
=case-sensitively by default, so'sales'does not match'Sales'. - MySQL's default collations are case-insensitive, so
'sales'does match'Sales'.
When you move queries between databases, check this first if the row counts differ.
Empty results are not errors
If no row passes the test, you get an empty result with the column headers and zero rows. The database reports no error.
SELECT first_name
FROM employees
WHERE department = 'Finance';This returns no rows. A typo such as 'Sale' behaves the same way. When a query unexpectedly returns nothing, suspect the literal first: check spelling, case, and stray spaces. Then check the type of the values you compare against.
UNKNOWN rows disappear silently
Because only TRUE keeps a row, rows with a NULL in the tested column vanish from the result, with no warning. Consider this query:
SELECT first_name, department
FROM employees
WHERE department <> 'Sales';| first_name | department |
|---|---|
| Chloe | Marketing |
| Dev | Support |
| Fay | Marketing |
Gus is missing. His department is NULL, and NULL <> 'Sales' is UNKNOWN, not TRUE. It is natural to expect "everyone not in Sales" to include him, but the database cannot say whether a missing value differs from 'Sales'.
Common errors
Using a column alias in WHERE
An alias defined in SELECT is not visible to WHERE in standard SQL.
-- Fails in PostgreSQL and MySQL: column "annual_salary" does not exist
SELECT first_name, salary * 12 AS annual_salary
FROM employees
WHERE annual_salary > 600000;The reason is evaluation order. The database runs WHERE before it computes the SELECT list, so the alias does not exist yet. The final chapter of this tutorial covers that order in full. Repeat the expression instead:
SELECT first_name, salary * 12 AS annual_salary
FROM employees
WHERE salary * 12 > 600000;SQLite accepts aliases in WHERE as a lenient extension. Do not rely on that if the query may run on another database.
Wrapping the column in a function
Conditions are easiest for the database to optimize when the bare column sits on one side. If an index exists on hire_date, a condition like WHERE hire_date >= '2022-01-01' can use it. A condition that wraps the column, like WHERE EXTRACT(YEAR FROM hire_date) = 2022, usually cannot. Both express a similar idea, but the first form scales better on large tables. Whether an index helps also depends on the database and the data.
Comparing mismatched types
Compare numbers with numbers and dates with dates. WHERE salary > '50000' may work in one database and error or behave oddly in another, because of implicit type conversion. Write numeric literals without quotes.
Aggregates in WHERE
You cannot filter on an aggregate such as AVG(salary) in WHERE, because aggregates are computed after rows are filtered. The HAVING clause handles that case, and it falls outside this tutorial.
Reuse the same WHERE to change data safely
The WHERE clause also controls which rows UPDATE and DELETE affect. With no WHERE, they affect every row. A habit worth building is to write the filter as a SELECT first and check the rows it returns:
SELECT employee_id, first_name, department
FROM employees
WHERE department = 'Support';Once the result is the set of rows you intend to change, reuse the identical WHERE in the UPDATE or DELETE.
Quick reference
| Situation | Behavior |
|---|---|
| Predicate TRUE | Row is kept |
| Predicate FALSE | Row is discarded |
| Predicate UNKNOWN (NULL involved) | Row is discarded |
| No row matches | Empty result, no error |
| Column alias in WHERE | Error in standard SQL; allowed in SQLite |
| Text literal | Single quotes |
| Text comparison case | Depends on database and collation |
Exercise
Using the sample table, you run SELECT first_name FROM employees WHERE department <> 'Sales';. Gus has a NULL department. Does Gus appear in the result, and why or why not?
Show answer
No. For Gus, NULL <> 'Sales' evaluates to UNKNOWN, not TRUE. WHERE keeps only rows where the predicate is TRUE, so Gus is discarded along with the FALSE rows. The result contains Chloe, Dev, and Fay.
Exercise
This query fails on PostgreSQL. Explain why and rewrite it so it works. SELECT first_name, salary + 5000 AS adjusted FROM employees WHERE adjusted > 55000;
Show answer
PostgreSQL evaluates WHERE before the SELECT list, so the alias adjusted does not exist yet when the filter runs. Repeat the expression in the filter: SELECT first_name, salary + 5000 AS adjusted FROM employees WHERE salary + 5000 > 55000; This returns Ana (57000), Chloe (63000), and Eli (66000).
Exercise
A colleague writes WHERE department = "Sales" with double quotes. What can happen on PostgreSQL, and what should they use instead?
Show answer
PostgreSQL treats double-quoted text as an identifier, so it looks for a column named Sales and raises an error. They should use single quotes: WHERE department = 'Sales'.