Why doesn't WHERE YEAR(order_date) = 2026 use the index on order_date?
Scenario
A report filtering a year of orders is slow even though order_date has an index. The query wraps the column in a function.
Interview answerTry answering first, then reveal
An index is sorted by the column's value, not by YEAR(order_date), so the database cannot seek into it and scans every row. Rewrite the filter so the column stands alone, as a half-open range: order_date >= '2026-01-01' AND order_date < '2027-01-01'. Such a predicate is called sargable (Search ARGument ABLE).
Explanation
A B-tree index on order_date lets the engine jump to the first 2026 date and read forward. With a function around the column, the engine would have to compute the function for every row to know which rows match, so it scans.
The same applies to CAST(col AS ...), col + 1 = 10, LOWER(email) = ... and LIKE '%abc'. Move the arithmetic to the constant side, or create an expression index (PostgreSQL) or indexed computed column (SQL Server) when the function is unavoidable.
The example uses SQLite (built into Python) so the plan output is real: SCAN means a full scan, SEARCH ... USING INDEX means an index range seek.
Worked example
Run on SQLite (built into Python) when this page was built; the results shown are the real output.
Sample data
CREATE TABLE orders (order_id INTEGER PRIMARY KEY, order_date TEXT, amount INTEGER);
CREATE INDEX ix_orders_date ON orders (order_date);Function on the column: full scan
EXPLAIN QUERY PLAN
SELECT SUM(amount) FROM orders
WHERE strftime('%Y', order_date) = '2026';SCAN orders
Half-open range: index seek
EXPLAIN QUERY PLAN
SELECT SUM(amount) FROM orders
WHERE order_date >= '2026-01-01' AND order_date < '2027-01-01';SEARCH orders USING INDEX ix_orders_date (order_date>? AND order_date<?)
In production
- Use half-open ranges (
>= start AND < next_start) for dates and timestamps.BETWEEN '2026-01-01' AND '2026-12-31'misses everything after midnight on 31 December for timestamp columns. - Lakehouse tables have no B-tree indexes, but the same rule decides data skipping: Delta and Iceberg keep min/max statistics per file, and a plain range filter on the column lets the engine skip files. Wrapping the column in a function can stop that pruning.
- Read the plan (
EXPLAIN,EXPLAIN ANALYZE) before and after a change rather than trusting intuition.
Common mistakes
- Comparing a date column to a string in a format the engine has to convert row by row.
- Implicit type conversion, such as comparing a
VARCHARcolumn to a number, which can apply a function to the column silently. - Adding more indexes instead of fixing the predicate.
Related questions
More on this topic in the SQL Interview Questions guide, or browse all SQL questions.