الانتقال إلى المحتوى
قواعد البياناتQuery Tuning· 6 دقائق للقراءة

Why WHERE YEAR(CreatedAt) = 2026 Skips Your Index: Sargable Predicates

An index can seek only on the values it stores. Wrap the column in a function, a leading wildcard or a type conversion, and every entry has to be read.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
محتويات المقال

The dashboard counts this year's orders with WHERE YEAR(CreatedAt) = 2026, and there's an index on CreatedAt, so it should be instant. In a test on SQL Server 2022 with 1,000,000 orders spread over ten years, it read 2,005 pages: every entry of the index. The same count written as a date range read 170. A second endpoint looked up customers by email, also indexed, and read 5,321 pages per call, because the application sent the email as nvarchar and the column is varchar.

The common misconception

The belief: if a column has an index, any condition on that column can use it.

It's a reasonable expectation, and the plan seems to confirm it: the YEAR() query's plan names IX_Orders_CreatedAt, because it did use the index, as a full scan. Optimizers are also clever enough to blur the rule. In the same test, CAST(CreatedAt AS date) = '2026-03-01' still became a seek that read 4 pages. When some functions work and others don't, it's natural to assume the database sorts it out.

What actually happens

A seek needs the stored value on one side

The index on CreatedAt holds CreatedAt values in order. For CreatedAt >= '2026-01-01' AND CreatedAt < '2027-01-01', the engine finds the first entry of 2026 and reads until the first entry of 2027. For YEAR(CreatedAt) = 2026, it has nothing to look up: the index doesn't store years, so the engine computes YEAR for every entry and keeps the matches. Microsoft calls the first kind a predicate, a search-argument-able condition that can use an index. PostgreSQL's docs describe the same boundary: a B-tree index is considered when an indexed column is compared with <, <=, =, >= or >, or with equivalent constructs like BETWEEN and IN.

Functions and arithmetic on the column

The cure is usually to move the work to the constant side. DATEADD(day, 30, CreatedAt) >= @today asks the engine to shift every stored date; CreatedAt >= DATEADD(day, -30, @today) computes one boundary and seeks to it. The same goes for arithmetic and string functions: in the test, Total * 1.14 > @limit read 2,377 pages against 25 for Total > @limit / 1.14, and LOWER(Email) = ... scanned the whole email index.

LIKE needs a fixed prefix

Email LIKE 'customer4242-%' is a range: everything from customer4242- up to the next prefix. Email LIKE '%@example.com' can match anywhere in the sorted order, so every entry has to be checked. PostgreSQL's docs state the same rule for B-trees: the pattern must be a constant anchored to the beginning of the string. They add a catch: in a database that doesn't use the C locale, the index needs a special operator class for LIKE to use it.

Hidden conversions count too

When a comparison mixes types, SQL Server converts the side with the lower precedence to the higher one, and nvarchar ranks above varchar. So a varchar column compared to an nvarchar parameter is the side that gets converted, and that puts a function on the column without anyone writing one. In the test, the plan showed CONVERT_IMPLICIT(nvarchar(200),[Email],0) and scanned the whole index, while a varchar(200) parameter seeked in 3 reads. The usual source is the driver: in the test, a .NET string passed with AddWithValue arrived as nvarchar(26).

Condition (1,000,000 rows, SQL Server 2022)PlanReadsSargable rewriteReads
YEAR(CreatedAt) = 2026Index Scan2,005CreatedAt >= '2026-01-01' AND CreatedAt < '2027-01-01'170
DATEADD(day, 30, CreatedAt) >= @todayIndex Scan2,005CreatedAt >= DATEADD(day, -30, @today)38
Email LIKE '%4242-3@example.com'Index Scan5,321A fixed prefix: LIKE 'customer4242-%'3
varchar column = nvarchar parameterIndex Scan5,321Parameter typed varchar(200)3

Keep the column bare

SQL
-- "Orders this year": YEAR() runs on every index entrySELECT COUNT(*) FROM dbo.OrdersWHERE YEAR(CreatedAt) = 2026;-- Tested: Index Scan, 2,005 reads-- "Placed in the last 30 days": arithmetic on the columnSELECT COUNT(*) FROM dbo.OrdersWHERE DATEADD(day, 30, CreatedAt) >= @today;-- Tested: Index Scan, 2,005 reads

The half-open range, >= the start and < the next start, also stays correct for any time of day, which BETWEEN '2026-01-01' AND '2026-12-31' doesn't. Both versions returned the same counts in the test.

When you can't change the query, index the expression instead:

SQL
-- A computed column with its own indexALTER TABLE dbo.Orders ADD CreatedYear AS YEAR(CreatedAt);CREATE INDEX IX_Orders_CreatedYear ON dbo.Orders (CreatedYear);-- Tested: WHERE YEAR(CreatedAt) = 2026 now seeks, 150 reads

In the test, SQL Server matched YEAR(CreatedAt) in the unchanged query to the computed column's index on its own. The PostgreSQL example follows the docs' lower(col1) pattern and wasn't run for this article.

How to apply it in your project

  1. Search for functions on indexed columnsGrep the code and the slowest queries for YEAR(, CAST(, CONVERT(, LOWER(, ISNULL( and arithmetic applied to columns in WHERE and JOIN clauses.
  2. Rewrite to bare-column rangesTurn date functions into half-open ranges and move arithmetic to the constant side. Check that the results match before and after.
  3. Check parameter types against column typesLook for CONVERT_IMPLICIT on a column in your plans, and fix the parameter's declared type in the data access code.
  4. Index the expression when the query can't changeUse a computed column with an index in SQL Server or an expression index in PostgreSQL, and remember that it adds write cost like any other index.

Key takeaways

  • An index can seek only for conditions on the column as stored; anything computed from it has to be evaluated entry by entry.
  • In the test, YEAR(CreatedAt) = 2026 read the whole index, 2,005 pages, while the equivalent range read 170.
  • LIKE can use a B-tree only with a fixed prefix; a leading % means a full scan.
  • Type mismatches hide a function on the column: an nvarchar parameter against a varchar column scanned 5,321 pages instead of 3.
  • When the query can't change, index the expression, and accept that it adds work to every write.

📚 المصادر

  1. Index Architecture and Design Guide — SQL Server, Microsoft Learn
  2. Data Type Precedence (Transact-SQL) — Microsoft Learn
  3. Index Types — PostgreSQL Documentation
  4. Indexes on Expressions — PostgreSQL Documentation
  5. Indexes on Computed Columns — SQL Server, Microsoft Learn

التعليقات (0)