- Home
- Interview Questions
- SQL
- Why can wrapping an indexed column in a function in WHERE ma…
Try answering first
In a real interview nobody shows you the answer. Think it through (or type it), then reveal the answers and rate yourself.
1 Answer
Short answer: An index stores the raw column values in sorted order. A predicate like YEAR(order_date) = 2024 filters on a computed value, so the optimizer usually cannot seek into the index and scans instead. Rewriting it as a range on the bare column makes it sargable, meaning it can use an index seek.
Detailed explanation
A B-tree index on order_date is sorted by order_date. To do a seek, the optimizer needs a start and end point in that sorted structure. For order_date >= '2024-01-01', it can jump straight to the first matching key and read forward.
With YEAR(order_date) = 2024, the condition is on the output of a function. Most optimizers do not reverse a function to work out a key range, so they evaluate the function on every row. That means a full table scan or full index scan. A predicate that can use an index seek is called sargable, short for Search ARGument ABLE.
Common non-sargable patterns:
- Functions on the column:
UPPER(email) = '[email protected]',CAST(created_at AS DATE) = ...,SUBSTRING(pan, 1, 3) = 'ABC'. Some engines handle a few special cases, such as SQL Server casting a datetime to date, but do not rely on this. - Arithmetic on the column:
price * 1.18 > 1000. Move the arithmetic to the constant side instead:price > 1000 / 1.18. - Leading wildcards:
name LIKE '%kumar'has no fixed prefix to seek on.LIKE 'kumar%'can use the index. - Implicit type conversion: comparing a VARCHAR mobile_no column to a number, as in
mobile_no = 9876543210, can force the database to convert every row's column value. Match the literal's or parameter's type to the column. - Wrapping for NULL handling:
COALESCE(discount, 0) = 0instead of(discount = 0 OR discount IS NULL).
Fixes, in order of preference:
- Rewrite the predicate so the bare column sits alone on one side.
- If the expression is unavoidable, index the expression itself. Options include expression indexes in PostgreSQL, function-based indexes in Oracle, functional key parts in MySQL 8.0.13 and later, and an indexed computed column in SQL Server.
- For case-insensitive matching, use a case-insensitive collation or a stored lowercase column instead of applying UPPER on every query.
- For 'contains' searches, use full-text search or a trigram index instead of
LIKE '%x%'.
Being sargable makes a seek possible, not guaranteed. If the filter matches a large share of the table, the optimizer may still choose a scan, and that can be the right choice.
Example
-- Index: CREATE INDEX idx_orders_date ON orders(order_date);
-- Non-sargable: function applied to every row
SELECT order_id, amount
FROM orders
WHERE YEAR(order_date) = 2024;
-- Sargable: half-open range on the bare column
SELECT order_id, amount
FROM orders
WHERE order_date >= '2024-01-01'
AND order_date < '2025-01-01';
-- Non-sargable arithmetic
SELECT * FROM products WHERE price * 1.18 > 1180;
-- Sargable rewrite
SELECT * FROM products WHERE price > 1000;
-- PostgreSQL: index the expression when you must filter on it
CREATE INDEX idx_users_lower_email ON users (LOWER(email));
SELECT * FROM users WHERE LOWER(email) = '[email protected]';Confirm the change with EXPLAIN or the actual execution plan. Look for an index seek or range scan instead of a full scan, and compare the rows examined.
Common mistakes
- Using
BETWEEN '2024-01-01' AND '2024-12-31'on a datetime column. This misses rows after midnight on 31 December. A half-open range (>=start and<next start) is safer. - Adding more indexes when the real problem is that the predicate cannot use the existing one.
- Passing parameters of the wrong type from application code, such as NVARCHAR against a VARCHAR column in SQL Server. This causes hidden conversions that do not appear in the SQL text.
- Assuming a sargable query will always seek, without checking the plan and the selectivity.
Follow-up questions
- How would you make a case-insensitive email lookup fast on a large users table?
- Why might the optimizer choose a full scan even when a usable index exists?
- How does column order in a composite index affect which WHERE clauses can use it?
Interview tip: Give the YEAR() example, rewrite it as a half-open date range on the spot, and mention verifying the result with EXPLAIN.
Reviewed by the Interview Questions editorial team · Last updated
How well did you know this?
Rate yourself to track progress, build your streak and get “didn't know” questions in your revision list.
Your Answer
More hard SQL questions
Related Questions
- What is the difference between a view and a materialized view, and when would you use each? · SQL · 1 ans
- How do you fetch the entire row with the highest salary in each department? · SQL · 1 ans
- What is the difference between COUNT(*), COUNT(column) and COUNT(DISTINCT column) in SQL? · SQL · 1 ans
- How does a recursive CTE execute step by step, and how do you stop it looping forever? · SQL · 1 ans
- Why does WHERE column = NULL return no rows, and how should you filter NULLs correctly? · SQL · 1 ans
- What are insertion, update and deletion anomalies, and how does normalization prevent them? · SQL · 1 ans
- How does BCNF differ from 3NF, and why can BCNF decomposition lose a dependency? · SQL · 1 ans
- How do ON DELETE CASCADE, SET NULL and RESTRICT work, and when are cascades dangerous? · SQL · 1 ans
🙋 Was this asked in your interview?
Which company? (optional — adds this question to the company's page)