Sub topic 13
Writing Predicates That Can Use Indexes
This chapter assumes you can write LIKE, IN, and BETWEEN conditions, and that you know NOT and NULL behave in surprising ways. You should also know what an index is: a sorted structure the database keeps beside a table so it can find rows without reading every one. The examples use standard SQL, with notes where PostgreSQL, MySQL, and SQL Server differ.
What "can use an index" means
Most relational databases build indexes as B-trees. A B-tree keeps values in sorted order, so it can jump to one position and read forward. This supports two operations:
- Seek to a value. Equality (
=) andINare a handful of seeks. - Scan a contiguous range.
<,>,BETWEEN, andLIKE 'abc%'all describe a stretch of the sorted order.
A predicate that the database can turn into one of these operations on the bare indexed column is called sargable (from "search argument able"). A predicate that is not sargable forces the database to read every row, or every index entry, and test each one.
The rule behind almost everything below is simple. The database can use the index only if it can describe the matching rows as a position or range in the sorted order of the stored column values. Anything that hides the column inside an expression breaks that.
LIKE: only the prefix helps
A B-tree on name can answer this efficiently:
SELECT id, name
FROM employees
WHERE name LIKE 'A%';All names starting with A sit together in sorted order. The database seeks to A and reads until it reaches B. In effect it rewrites the pattern as name >= 'A' AND name < 'B'.
A pattern that starts with a wildcard has no such range:
SELECT id, name
FROM employees
WHERE name LIKE '%son';Names ending in son are scattered across the whole index. The database must test every entry. A wildcard in the middle, as in 'AB_-%', still helps, but only for the literal prefix before the first wildcard (AB). The rest is checked row by row against the candidates that the prefix found.
Several things affect whether a prefix LIKE uses an index:
- Collation and locale. In PostgreSQL with a non-
Clocale, a default B-tree index cannot serveLIKE 'A%'. Create the index with thetext_pattern_opsoperator class:CREATE INDEX idx_employees_name ON employees (name text_pattern_ops);. MySQL and SQL Server generally allow a prefixLIKEon a normal index. - Parameters. With
LIKE ?and a value supplied at run time, some databases cannot know whether the pattern starts with a wildcard when they build the plan. Check your database's behavior. - Suffix and substring searches. For
'%son', one option is to store and index a reversed copy of the string and search for'nos%'. For'%son%', use a feature built for it, such as PostgreSQL'spg_trgmtrigram indexes or a full-text index.
Wrapping the column breaks the seek
The case-insensitive example from earlier in this tutorial has a cost:
SELECT id, name
FROM employees
WHERE LOWER(name) LIKE 'a%';The index stores name, not LOWER(name). The sorted order of the stored values says nothing about where lowercase a values would be, so the database cannot seek. It computes LOWER(name) for every row.
You have three ways to fix this:
- Index the expression. The index then stores the computed values.
- Use a case-insensitive collation on the column, so plain comparisons ignore case and no function is needed.
- Store a normalized copy in a separate column, and keep it up to date.
The first option looks like this in PostgreSQL:
CREATE INDEX idx_employees_lower_name
ON employees (LOWER(name) text_pattern_ops);
SELECT id, name
FROM employees
WHERE LOWER(name) LIKE 'a%';MySQL 8.0.13 and later supports functional indexes with the expression in an extra pair of parentheses: CREATE INDEX idx_lower_name ON employees ((LOWER(name)));. SQL Server has no index on an expression. You create a computed column, ALTER TABLE employees ADD name_lower AS LOWER(name);, and index that.
An expression index only helps when the query repeats the expression exactly. An index on LOWER(name) does not help UPPER(name) LIKE 'A%'.
The same problem appears with arithmetic and conversions:
-- Not sargable: arithmetic on the column
SELECT id FROM employees WHERE salary * 12 > 600000;
-- Sargable: move the arithmetic to the constant side
SELECT id FROM employees WHERE salary > 600000 / 12;Always rewrite so the column stands alone on one side of the comparison.
IN and the index
IN with a list of constants is a set of equality tests, so each value is a seek:
SELECT id, name, department
FROM employees
WHERE department IN ('Sales', 'Marketing', 'Support');With an index on department, the database seeks three times. This is usually as efficient as the equivalent chain of OR conditions, and it is easier to read. Very long lists have costs. They enlarge the statement, can exceed parameter limits, and make planning slower. If the list has thousands of values, load them into a temporary table and join to it.
IN (subquery) is treated by modern optimizers as a semi-join, a join that returns each outer row at most once. The planner can choose to look up the inner results through an index on the outer table, or the other way around. You do not control that choice directly. Check that the join columns are indexed on both sides.
BETWEEN and date ranges
BETWEEN is a range, so one seek locates the lower bound and the scan reads to the upper bound:
SELECT id, name, salary
FROM employees
WHERE salary BETWEEN 50000 AND 70000;For dates, the same index-friendly form is also the correct one. The half-open range covers every timestamp in March, and it compares the bare column:
SELECT id, created_at
FROM orders
WHERE created_at >= '2026-03-01'
AND created_at < '2026-04-01';The tempting alternative strips the time part first:
-- Not sargable: the column is wrapped in CAST
SELECT id, created_at
FROM orders
WHERE CAST(created_at AS date) = '2026-03-15';
-- Sargable: a half-open range for one day
SELECT id, created_at
FROM orders
WHERE created_at >= '2026-03-15'
AND created_at < '2026-03-16';Some optimizers recognize the cast-to-date pattern and rewrite it. Do not depend on that, because the half-open form works everywhere. Functions such as YEAR(created_at) = 2026 and EXTRACT(MONTH FROM created_at) = 3 have the same problem.
Negation usually scans
A negative predicate describes everything except a set, which is generally most of the table:
SELECT id, name FROM employees WHERE name NOT LIKE 'A%';
SELECT id, name FROM employees WHERE department NOT IN ('Sales', 'Support');
SELECT id, salary FROM employees WHERE salary NOT BETWEEN 50000 AND 70000;NOT BETWEEN is two ranges (below 50000 or above 70000), and a database can sometimes seek to both ends. The others read most of the index or table. If a negated condition matches only a few rows, the planner may still use an index, but it cannot rely on a seek to find them. Combine negations with a selective positive condition so the index serves that part.
For "rows with no match in another table", NOT EXISTS is the safe and fast form:
SELECT c.id, c.name
FROM customers c
WHERE NOT EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = c.id
);With an index on orders.customer_id, the database can check each customer with one seek. It is also immune to the NULL trap that affects NOT IN.
OR and composite indexes
OR across different columns is hard to serve with one index. Databases may combine two indexes (a bitmap OR in PostgreSQL, an index merge in MySQL), or they may scan the table. When both sides test the same column, write IN instead.
A composite index covers several columns in a fixed order. The database can seek on leading columns, but only the first range-like column can narrow the search. Columns after it are checked within that range. Consider this index:
CREATE INDEX idx_employees_dept_salary
ON employees (department, salary);It serves this query well, since the IN gives a few seeks and BETWEEN gives a range inside each:
SELECT id, name, salary
FROM employees
WHERE department IN ('Sales', 'Support')
AND salary BETWEEN 40000 AND 60000;It does not help a query that filters only on salary, because salary is not the leading column. A good default is to put equality and IN columns first, then the range column (BETWEEN, <, a prefix LIKE) last.
Parentheses matter here too. In the earlier query department IN (...) AND (name LIKE 'A%' OR salary BETWEEN ...), the OR inside the parentheses limits how well one index can serve the whole condition. The department part can still use an index, and the parenthesized part is then checked on the rows that remain.
A summary of patterns
| Predicate | Index use on a plain B-tree index |
|---|---|
| `name LIKE 'Ann%'` | Range scan on the prefix (locale caveats apply) |
| `name LIKE '%son'` | Full scan |
| `LOWER(name) = 'ann'` | Full scan unless an expression index exists |
| `department IN ('A','B')` | One seek per value |
| `salary BETWEEN 1 AND 9` | Range scan |
| `CAST(created_at AS date) = d` | Full scan, usually |
| `created_at >= d1 AND created_at < d2` | Range scan |
| `NOT IN`, `NOT LIKE`, `<>` | Usually a scan |
| `x IS NULL` | Depends on database and index type |
Checking what the database does
Do not guess. Ask the database for its plan:
EXPLAIN
SELECT id, name
FROM employees
WHERE name LIKE 'A%';In PostgreSQL, look for Index Scan, Index Only Scan, or Bitmap Index Scan versus Seq Scan. MySQL shows the chosen index in the key column. SQL Server's graphical plan shows Index Seek or Index Scan.
A sargable predicate does not guarantee an index is used. On a small table, or when a predicate matches a large share of the rows (a common letter like S, or a wide range), a sequential scan is cheaper than jumping between the index and the table. The planner's choice is based on statistics, so run ANALYZE (PostgreSQL) or the equivalent after large data changes. Test on data of realistic size.
Exercise
A table orders has an index on created_at. The query WHERE EXTRACT(YEAR FROM created_at) = 2026 is slow. Rewrite it so the index can be used, and say why the rewrite works.
Show answer
Use a half-open range: WHERE created_at >= '2026-01-01' AND created_at < '2027-01-01'. The original applies a function to the column, so the database cannot map the condition to a position in the sorted index. The rewrite compares the bare column to constants, which describes one contiguous range of the index.
Exercise
You need case-insensitive prefix searches such as LOWER(email) LIKE 'jo%' to be fast in PostgreSQL. What index would you create, and what happens if a query uses UPPER(email) instead?
Show answer
Create an expression index such as CREATE INDEX idx_users_lower_email ON users (LOWER(email) text_pattern_ops);. A query using UPPER(email) cannot use it, because an expression index only matches the exact expression it was built on.