Covers what makes a predicate SARGable, the common non-sargable patterns (functions and arithmetic on columns, implicit conversions, leading wildcards, ISNULL/COALESCE, OR across columns, catch-all queries) and their rewrites, including computed columns and the CAST to date exception.
A predicate is SARGable (Search ARGument-able) when the optimiser can turn it into a seek range on an index. The rule: leave the column bare and put any calculation on the other side.
YEAR(OrderDate) = 2026 scans; OrderDate >= '2026-01-01' AND OrderDate < '2027-01-01' seeks.Price * 1.1 > 100 scans; Price > 100 / 1.1 seeks.varchar column vs nvarchar parameter) often scans; match types.LIKE 'abc%' seeks; LIKE '%abc' cannot.ISNULL(col, 0) = 0 scans; col = 0 OR col IS NULL seeks.When the expression is unavoidable, index a persisted computed column. Trade-off: the rewrite is free; the computed column costs storage and writes.
"SARGable means the predicate can be used as a search argument: the optimiser can work out a start and end point in the index's sorted order and seek straight to it. An index on OrderDate is sorted by OrderDate, not by YEAR of OrderDate, so the moment you wrap the column in a function, SQL Server has to compute that function for every row and compare, which means a scan. The rule I follow is: leave the column bare and move the work to the other side of the comparison.
The usual offenders: functions on the column, like YEAR, DATEADD, UPPER or LTRIM, which I rewrite as ranges or fix in the data. Arithmetic on the column, like Price times 1.1 greater than 100, where I divide the constant instead. Implicit conversions, where the column has to be converted to match the parameter's type: a varchar column compared with an nvarchar parameter is the classic one from .NET, and the plan shows a CONVERT_IMPLICIT warning. Leading wildcards, because LIKE '%smith' gives no starting point in a sorted index. ISNULL or COALESCE around the column, which I rewrite as an OR with IS NULL. And catch-all search procedures, WHERE @Name IS NULL OR Name = @Name, which compile one plan for every combination and end up scanning.
The mistake I see is people rewriting what they think is non-sargable without checking. CAST of a datetime column to date is a special case the optimiser can still seek on, and a scan isn't always wrong if the query returns most of the table. For example, at [company] we [had a dashboard filtering on CONVERT(varchar, CreatedAt, 112) = @day; rewriting it as a half-open date range took it from [1.2] million logical reads to [300]]. I confirm with the actual plan: a Seek with the right Seek Predicates, and logical reads before and after."
| Non-sargable | SARGable rewrite |
|---|---|
WHERE YEAR(OrderDate) = 2026 |
WHERE OrderDate >= '20260101' AND OrderDate < '20270101' |
WHERE DATEADD(day, 30, OrderDate) > SYSUTCDATETIME() |
WHERE OrderDate > DATEADD(day, -30, SYSUTCDATETIME()) |
WHERE Price * 1.1 > 100 |
WHERE Price > 100 / 1.1 |
WHERE UPPER(Email) = @e (case-insensitive collation) |
WHERE Email = @e (the collation already ignores case) |
WHERE LEFT(Postcode, 2) = '20' |
WHERE Postcode LIKE '20%' |
WHERE ISNULL(DiscountCode, '') = '' |
WHERE DiscountCode = '' OR DiscountCode IS NULL |
WHERE AccountNo = @p (varchar column, nvarchar @p) |
Declare @p as varchar(20) |
WHERE Surname LIKE '%son' |
Indexed reversed computed column, full-text, or Azure AI Search |
WHERE (@c IS NULL OR CustomerId = @c) AND (@s IS NULL OR Status = @s) |
OPTION (RECOMPILE) or dynamic SQL with sp_executesql |
A claims search used WHERE CONVERT(date, LodgedAt) = @day OR ISNULL(ClaimRef, '') = @ref. Rewriting it as two sargable branches combined with UNION ALL (date range, and ClaimRef = @ref) took logical reads from 410,000 to 35 and p95 from 2.1 s to 8 ms.
Checks whether the candidate can recognise and rewrite non-sargable predicates and connect them to .NET parameter types.
Green flags
Red flags
A B-tree is sorted by the stored column value. A seek needs a range [start, end] in that order:
Index on OrderDate: ...2025-12-30 | 2026-01-01 ... 2026-12-31 | 2027-01-01...
^ seek start ^ seek end
YEAR(OrderDate) = 2026 -> the tree is not sorted by YEAR(...) as an expression
-> compute YEAR() for every row -> scan + filter
Some functions are order-preserving in principle, but SQL Server only recognises a few special cases, so assume a function on the column blocks the seek.
WHERE CAST(OrderDateTime AS date) = '2026-11-19' can still seek: the optimiser rewrites it into a dynamic range (GetRangeThroughConvert). The estimate can be worse than a plain range though, so I still prefer the explicit half-open range.
When types differ, SQL Server converts the lower-precedence type to the higher. nvarchar beats varchar, so a varchar column compared with an nvarchar parameter converts the column: the plan shows CONVERT_IMPLICIT(nvarchar(50), [AccountNo], 0) and a 'Type conversion may affect seek plan' warning. With a Windows collation SQL Server can sometimes still produce a range seek, but with a SQL collation (such as the common SQL_Latin1_General_CP1_CI_AS) it scans, and estimates suffer either way. The reverse (an nvarchar column with a varchar value) converts the value and is harmless. int column vs varchar value converts the value too (int has higher precedence).
LIKE 'abc%': a range seek from 'abc' to the next prefix.LIKE '%abc' or '%abc%': no start point; scan.REVERSE(Surname) queried with LIKE REVERSE(@suffix) + '%'.ISNULL(col, x) is a function on the column. col = 0 OR col IS NULL can be two seeks. OR across different columns can only seek if each column has an index (index union), and often scans; UNION ALL of two sargable queries is the reliable rewrite. Catch-all predicates (@p IS NULL OR col = @p) compile a single plan valid for every parameter combination; OPTION (RECOMPILE) lets the optimiser embed the values and remove the dead branches, while dynamic SQL built from only the supplied filters (still parameterised) gives one cached plan per shape.
When you must filter on an expression, add a computed column, PERSISTED if it is non-deterministic-safe and you want it stored, and index it. The optimiser matches the expression in the query to the computed column even if the query does not name it, provided the expression is identical and the SET options are correct.
OrderDate; compare YEAR(OrderDate) = 2026 with the range rewrite using STATISTICS IO.varchar(20) column with an nvarchar(20) parameter via sp_executesql; find CONVERT_IMPLICIT in the plan XML.CAST(OrderDate AS date) = @d with the half-open range: both seek, compare estimated rows.REVERSE(Surname), index it and run a suffix search.OPTION (RECOMPILE).Schema, non-sargable predicates and their rewrites.
CREATE TABLE dbo.Customers
(
CustomerId int IDENTITY NOT NULL CONSTRAINT PK_Customers PRIMARY KEY,
AccountNo varchar(20) NOT NULL, -- varchar: watch .NET nvarchar parameters
Surname nvarchar(100) NOT NULL,
Email nvarchar(256) NOT NULL, -- case-insensitive collation
CreatedAt datetime2(3) NOT NULL
);
CREATE INDEX IX_Customers_AccountNo ON dbo.Customers (AccountNo);
CREATE INDEX IX_Customers_CreatedAt ON dbo.Customers (CreatedAt);
CREATE INDEX IX_Customers_Email ON dbo.Customers (Email);
-- 1. Function on the column: scan
SELECT CustomerId FROM dbo.Customers WHERE YEAR(CreatedAt) = 2026;
-- Rewrite: half-open range, seek
SELECT CustomerId FROM dbo.Customers WHERE CreatedAt >= '20260101' AND CreatedAt < '20270101';
-- 2. Redundant function under a case-insensitive collation: scan
SELECT CustomerId FROM dbo.Customers WHERE LOWER(Email) = LOWER(@Email);
-- Rewrite: the collation already compares case-insensitively
SELECT CustomerId FROM dbo.Customers WHERE Email = @Email;
-- 3. Implicit conversion of the column (nvarchar parameter vs varchar column): scan + warning
EXEC sp_executesql N'SELECT CustomerId FROM dbo.Customers WHERE AccountNo = @a', N'@a nvarchar(20)', @a = N'AC-1001';
-- Rewrite: matching type, seek
EXEC sp_executesql N'SELECT CustomerId FROM dbo.Customers WHERE AccountNo = @a', N'@a varchar(20)', @a = 'AC-1001';
-- 4. Leading wildcard: no start point. Index a reversed computed column for suffix searches.
ALTER TABLE dbo.Customers ADD SurnameReversed AS REVERSE(Surname) PERSISTED;
CREATE INDEX IX_Customers_SurnameReversed ON dbo.Customers (SurnameReversed);
SELECT CustomerId FROM dbo.Customers WHERE SurnameReversed LIKE REVERSE(N'son') + N'%';
-- 5. Catch-all search: one plan for all combinations scans. Let each call compile with its values.
CREATE OR ALTER PROCEDURE dbo.SearchCustomers @AccountNo varchar(20) = NULL, @From datetime2(3) = NULL
AS
SELECT CustomerId, Surname
FROM dbo.Customers
WHERE (@AccountNo IS NULL OR AccountNo = @AccountNo)
AND (@From IS NULL OR CreatedAt >= @From)
OPTION (RECOMPILE);
The .NET side: Dapper sends string as nvarchar(4000) by default, so declare varchar explicitly for varchar columns, and build date ranges rather than calling functions on columns.
namespace Crm.Data;
using System.Data;
using Dapper;
using Microsoft.Data.SqlClient;
public sealed class CustomerLookup(string connectionString)
{
public async Task<int?> FindByAccountAsync(string accountNo, CancellationToken ct)
{
await using var conn = new SqlConnection(connectionString);
var cmd = new CommandDefinition(
"SELECT CustomerId FROM dbo.Customers WHERE AccountNo = @AccountNo",
new { AccountNo = new DbString { Value = accountNo, IsAnsi = true, Length = 20 } }, // varchar(20)
cancellationToken: ct);
return await conn.QuerySingleOrDefaultAsync<int?>(cmd);
}
public async Task<IReadOnlyList<int>> CreatedInYearAsync(int year, CancellationToken ct)
{
await using var conn = new SqlConnection(connectionString);
var from = new DateTime(year, 1, 1);
var cmd = new CommandDefinition(
"SELECT CustomerId FROM dbo.Customers WHERE CreatedAt >= @From AND CreatedAt < @To",
new { From = from, To = from.AddYears(1) }, // half-open range: sargable
cancellationToken: ct);
return (await conn.QueryAsync<int>(cmd)).AsList();
}
}
YEAR, CONVERT, LTRIM, UPPER). Why it is wrong: the index is sorted by the raw value, so the function must run on every row. Instead: rewrite as a range or fix the data once.BETWEEN '2026-01-01' AND '2026-01-31 23:59:59' for date ranges. Why it is wrong: it misses fractional seconds in datetime2. Instead: half-open ranges >= start AND < next.nvarchar parameters for varchar columns (Dapper and ADO.NET default for string). Why it is wrong: the column is converted, causing scans and bad estimates. Instead: DbString { IsAnsi = true }, SqlDbType.VarChar, or HasColumnType("varchar(20)") / IsUnicode(false) in EF Core.UPPER()/LOWER() on both sides under a case-insensitive collation. Why it is wrong: it adds nothing but a scan. Instead: rely on the collation, or use a case-insensitive computed column if the collation is case-sensitive.(@p IS NULL OR col = @p) with a cached plan. Why it is wrong: the plan must handle every combination, so it scans. Instead: OPTION (RECOMPILE) or parameterised dynamic SQL.LIKE '%term%' to use an index. Why it is wrong: there is no start point in a sorted structure. Instead: full-text search or a search service.CAST(col AS date) = @d as if it were non-sargable. Why it is wrong: SQL Server can seek on it (a special case). Instead: check the plan; prefer a plain range for better estimates.SARGability is the cheapest performance fix there is: no new index, no hardware, just moving work off the column. I check for it whenever a plan scans an index that has the right leading column, and I look at plan warnings for CONVERT_IMPLICIT, which in .NET codebases is almost always a parameter type mismatch that one line of configuration fixes everywhere. In EF Core the same problem appears as LINQ like o.CreatedAt.Year == year or c.Email.ToLower() == email, which translate faithfully into functions on the column, so I review the generated SQL (ToQueryString() or logging) for hot queries.
It is not always worth rewriting. If the query legitimately returns most of the table, a scan is the right plan and sargability changes nothing. If the rule truly depends on a computed expression (for example a tax calculation across several columns), a computed column or a precomputed value written by the application is the honest fix, not contortions in the WHERE clause. And for queries that run once a day over small tables, readability can win.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Rewrite the predicate | Almost always possible | None | Business rule truly needs the expression |
| Indexed computed column | Expression is fixed and frequent | Storage, write cost, SET options | Many different expressions |
| Fix the data (trim on write, normalise case) | Dirty data forces functions | One-off migration and validation | Data owned by another system |
| OPTION (RECOMPILE) | Catch-all searches, low frequency | Compile CPU per call | Thousands of calls per second |
| Full-text or search service | Contains-anywhere text search | Another component to run | Prefix searches (LIKE 'abc%' already seeks) |
Because the generated SQL applies the function to every row (LOWER([c].[Email]) = @email, DATEPART(year, [o].[PlacedAt]) = 2026), so SQL Server can't seek an index on the raw column. It scans the whole index instead, which costs CPU and reads proportional to the table and gets worse as data grows. Fixes: express dates as a half-open range (WHERE [o].[PlacedAt] >= @start AND [o].[PlacedAt] < @end); rely on the database's case-insensitive collation instead of ToLower(), so no function is needed at all; or index a persisted computed column when you really need the derived value.
A composite index is a B+ tree sorted by the first column, then by the second within each first value, like a phone book sorted by surname then first name.
(CustomerId, OrderDate, Status) supports CustomerId = @c, CustomerId = @c AND OrderDate >= @d, but not OrderDate >= @d alone (that scans; SQL Server has no skip-scan).Trade-off: one well-ordered index can serve several queries; the wrong order serves none.
How to tell it (STAR)
**S:** At [company] a reconciliation report running every five minutes was the top consumer on our Azure SQL database. **T:** I needed to bring DTU down before we scaled up the tier. **A:** Query Store pointed me at the report, the plan showed an index scan with the CONVERT on CreatedAt as a filter and no seek predicate, so I rewrote it as a half-open date range with a typed parameter, then searched for the same pattern elsewhere and fixed [7] more queries. **R:** That query went from [1.2 million] reads to [300], DTU dropped from [85]% to [40]%, and we avoided the tier upgrade.
Last updated 23 Nov 2026.