
Why WHERE YEAR(CreatedAt) = 2026 Skips Your Index: Sargable Predicates
- كاتب موثّق
محتويات المقال
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
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
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
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
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).
YEAR(CreatedAt) = 2026 | CreatedAt >= '2026-01-01' AND CreatedAt < '2027-01-01' | |||
DATEADD(day, 30, CreatedAt) >= @today | CreatedAt >= DATEADD(day, -30, @today) | |||
Email LIKE '%4242-3@example.com' | LIKE 'customer4242-%' | |||
varchar column = nvarchar parameter | varchar(200) |
Keep the column bare
-- "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-- Same results, bare column on the left: both seekSELECT COUNT(*) FROM dbo.OrdersWHERE CreatedAt >= '2026-01-01' AND CreatedAt < '2027-01-01';-- Tested: Index Seek, 170 readsSELECT COUNT(*) FROM dbo.OrdersWHERE CreatedAt >= DATEADD(day, -30, @today);-- Tested: Index Seek, 38 reads>= 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.
-- 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-- An index on an expression (example from the PostgreSQL docs)CREATE INDEX orders_lower_email_idx ON orders (lower(email));SELECT id FROM orders WHERE lower(email) = 'ana@example.com';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
Search for functions on indexed columns Grep the code and the slowest queries for YEAR(,CAST(,CONVERT(,LOWER(,ISNULL(and arithmetic applied to columns inWHEREandJOINclauses.Rewrite to bare-column ranges Turn date functions into half-open ranges and move arithmetic to the constant side. Check that the results match before and after. Check parameter types against column types Look for CONVERT_IMPLICITon a column in your plans, and fix the parameter's declared type in the data access code.Index the expression when the query can't change Use 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) = 2026read the whole index, 2,005 pages, while the equivalent range read 170.LIKEcan use a B-tree only with a fixed prefix; a leading%means a full scan.Type mismatches hide a function on the column: an nvarcharparameter against avarcharcolumn 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.
التعليقات (0)