1. Home
  2. Interview Questions
  3. SQL
  4. 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

0 0
InterviewQuestions Team ✔ Expert answer ✔ Best 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) = 0 instead of (discount = 0 OR discount IS NULL).

Fixes, in order of preference:

  1. Rewrite the predicate so the bare column sits alone on one side.
  2. 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.
  3. For case-insensitive matching, use a case-insensitive collation or a stored lowercase column instead of applying UPPER on every query.
  4. 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

All hard questions →

Related Questions

‹
Q4 of 10 · SQL
Next ›

Interview Questions

Free interview questions and answers, MCQ practice, online tests, mock interviews and group discussions — everything you need to crack your next interview.
📍 Dasardot LLC
1309 Coffeen Avenue STE 1200
Sheridan, Wyoming 82801
USA