📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What does SARGable mean in SQL Server? Show me predicates that prevent an index seek, such as functions on columns, arithmetic, implicit conversions, leading wildcards and ISNULL, and rewrite each one so it can seek.

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.

Mid-Level Sql Intermediate implicit-conversion indexes query-performance sargability sql-server t-sql

🎯 Key points

  • SARGable = Search ARGument-able: the optimiser can turn the predicate into a seek range on the index
  • Leave the column bare; move the work to the other side of the comparison
  • YEAR(OrderDate) = 2026 becomes OrderDate >= '2026-01-01' AND OrderDate < '2027-01-01'
  • Implicit conversion on the column side (CONVERT_IMPLICIT, 'may affect seek plan' warning) blocks seeks and skews estimates; match parameter types
  • LIKE 'abc%' can seek; LIKE '%abc' cannot (use full-text, a reversed computed column or a search service)
  • ISNULL(col, 0) = 0 becomes (col = 0 OR col IS NULL); catch-all (@p IS NULL OR col = @p) needs OPTION (RECOMPILE) or dynamic SQL
  • Verify in the actual plan: Seek Predicates present, no residual Filter on the expression, logical reads before and after
  • Indexed persisted computed column when the expression is unavoidable; CAST(datetime AS date) is a special case that can still seek (check the plan)

⏱ 30-second answer

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.
  • An implicit conversion of the column (e.g. 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.

🗣 Full answer (senior)

How I would answer this in an interview

"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."


Rewrites

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

Production example

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.

🔍 What the interviewer is checking

Checks whether the candidate can recognise and rewrite non-sargable predicates and connect them to .NET parameter types.

Green flags

  • States the bare-column rule and rewrites ranges correctly with half-open intervals
  • Explains implicit conversion direction via data type precedence
  • Knows LIKE prefix vs leading wildcard and catch-all query fixes
  • Verifies with the actual plan and logical reads

Red flags

  • Thinks adding an index fixes a function on the column
  • Uses BETWEEN with 23:59:59
  • Unaware that .NET strings map to nvarchar

📚 Learn in depth

1. Why a seek needs a bare column

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.

2. The CAST to date exception

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.

3. Implicit conversions and data type precedence

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).

4. LIKE patterns

  • LIKE 'abc%': a range seek from 'abc' to the next prefix.
  • LIKE '%abc' or '%abc%': no start point; scan.
  • Suffix searches: an indexed persisted computed column REVERSE(Surname) queried with LIKE REVERSE(@suffix) + '%'.
  • Contains-anywhere searches: full-text search, or an external search index.

5. ISNULL, OR and catch-all queries

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.

6. Computed columns

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.

Try it yourself

  1. Load 2 million orders with an index on OrderDate; compare YEAR(OrderDate) = 2026 with the range rewrite using STATISTICS IO.
  2. Query a varchar(20) column with an nvarchar(20) parameter via sp_executesql; find CONVERT_IMPLICIT in the plan XML.
  3. Compare CAST(OrderDate AS date) = @d with the half-open range: both seek, compare estimated rows.
  4. Add a computed column REVERSE(Surname), index it and run a suffix search.
  5. Write a catch-all search procedure and compare plans with and without OPTION (RECOMPILE).

💻 Code

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();
    }
}

⚠ Common mistakes

  • Mistake: Wrapping the column in a function (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.
  • Mistake: Using 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.
  • Mistake: Sending 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.
  • Mistake: 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.
  • Mistake: Catch-all (@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.
  • Mistake: Expecting 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.
  • Mistake: Rewriting 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.

🏛 Senior insight: trade-offs

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)

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions ToLower() or .Year in LINQ queries. Why: Checks the EF Core LINQ version of the same problem.
    How to answer

    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.

  2. When: Candidate rewrites a predicate but the index leads with another column. Why: Checks that a sargable predicate also needs the right index column order.
    How to answer

    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.

    • Leftmost-prefix rule: SQL Server can seek only when the query constrains the leading column(s). (CustomerId, OrderDate, Status) supports CustomerId = @c, CustomerId = @c AND OrderDate >= @d, but not OrderDate >= @d alone (that scans; SQL Server has no skip-scan).
    • Put equality columns first, then the range column. After a range, later columns can only be filtered as a residual predicate, not seeked.
    • The order also lets the index return rows already sorted, avoiding a Sort.

    Trade-off: one well-ordered index can serve several queries; the wrong order serves none.

🛠 Real-world problems: how you handle them

Daily report query scanning because of a CONVERT on the date column
Situation
A [payments reconciliation] report on Azure SQL ran every 5 minutes against a [150-million-row] transactions table, filtering a single day with `WHERE CONVERT(varchar(8), CreatedAt, 112) = @day`.
Signals
Azure SQL DTU at [85]% in business hours; Query Store showed the report as the top query by logical reads ([1.2 million] per run); Intelligent Insights flagged increased resource consumption.
Investigation
The actual plan showed a parallel scan of `IX_Transactions_CreatedAt` with a Compute Scalar and Filter on the CONVERT expression; estimated rows were a fixed guess far from actual. Seek Predicates were empty, confirming the index was only being scanned.
Resolution
Immediate: rewrote the predicate as `CreatedAt >= @dayStart AND CreatedAt < DATEADD(day, 1, @dayStart)` with a `datetime2` parameter and deployed the hotfix. The plan became a seek: [300] logical reads, [5] ms. Long-term: searched the codebase for other functions on indexed columns and fixed [7] more.
Prevention
A SQL code-review checklist item for functions on columns; a Query Store report of top queries by reads reviewed each sprint; a static check that flags `CONVERT(`/`YEAR(` in WHERE clauses of repository SQL.

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.

↩ Usually asked after

More in Indexes

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me