Search-Friendly SQL Server Queries: Date Ranges, LIKE Patterns, and Computed Columns

Search-Friendly SQL Server Queries: Date Ranges, LIKE Patterns, and Computed Columns

A slow query does not always mean that an index is missing. An index may exist, yet the WHERE predicate can make it difficult for the Database Engine to use that index efficiently. Common examples include applying a function to the indexed column, converting the column value during comparison, or starting a pattern search with a wildcard.

This article presents a reusable way to design predicates that are friendly to index access. The term SARGable is commonly used for search arguments that allow the optimizer to use a column comparison as part of an access strategy. It does not guarantee a particular execution plan, but it usually gives the optimizer a better starting point.

What makes a predicate search-friendly?

In a simple equality predicate, the column is compared directly with a parameter:

SELECT OrderId, CustomerId, OrderDate
FROM Sales.Orders
WHERE CustomerId = @CustomerId;

With a suitable index on CustomerId, this condition can define a useful starting point for locating rows. By contrast, wrapping the column in a function may prevent the optimizer from using the index key as directly:

-- Less favorable
WHERE YEAR(OrderDate) = @OrderYear

-- More favorable
WHERE OrderDate >= @StartDate
  AND OrderDate <  @EndDate;

The second form compares the stored column with an interval. It still does not guarantee an index seek: data distribution, cardinality estimates, statistics, selectivity, and index coverage all affect plan choice. The important improvement is that the column remains available for a range comparison.

Use half-open intervals for dates and timestamps

A common date-filtering mistake is to calculate the final second of a period manually:

-- Fragile approach
WHERE CreatedAt BETWEEN '2026-01-01 00:00:00'
                    AND '2026-01-31 23:59:59';

This can omit values with fractional seconds or higher precision. It also encourages assumptions about the underlying data type. A more robust pattern includes the start boundary and excludes the next period’s start:

DECLARE @StartDate date = '20260101';
DECLARE @EndDate   date = '20260201';

SELECT OrderId, CreatedAt
FROM Sales.Orders
WHERE CreatedAt >= @StartDate
  AND CreatedAt <  @EndDate;

This is the [start, end) interval model. It works for days, months, hours, and other periods without requiring a fabricated “last moment” value. The same principle applies when the column is datetime2.

Define time-zone semantics before optimizing

An application may store UTC values, local wall-clock values, or datetimeoffset. Do not change the meaning of the data while trying to improve performance. Calculate boundaries in the intended time zone at the application or service boundary and pass them as parameters. Applying a time-zone conversion to the column for every candidate row can make both reasoning and index access harder.

Convert the parameter, not the column

Converting an input parameter inside a query is often acceptable:

WHERE EventDate >= CONVERT(date, @InputDate, 112);

The more problematic form applies the conversion to the stored column:

-- Usually less favorable
WHERE CONVERT(date, EventDate) = @DateOnly;

Rewrite the condition as a range:

WHERE EventDate >= @DateOnly
  AND EventDate <  DATEADD(day, 1, @DateOnly);

Here, DATEADD operates on the parameter side while EventDate remains a directly comparable column. Parameters should also use the same logical data type as the column whenever possible. This avoids unnecessary conversion and makes the contract between the application and database clearer.

LIKE patterns have different access characteristics

A pattern with a fixed beginning, such as LIKE 'Ada%', may provide a useful range on a character column when a compatible index exists:

SELECT CustomerId, DisplayName
FROM Sales.Customers
WHERE DisplayName LIKE @Prefix; -- example value: 'Ada%'

A pattern such as LIKE '%ada%' searches for text anywhere in the value. Because the pattern starts with a wildcard, a conventional B-tree index may not be able to derive a narrow starting range. On a large table, this can result in many rows being examined.

Choose the search technology according to the requirement:

  • Use equality for an exact match.
  • Use a trailing wildcard for prefix matching when that matches the business need.
  • Consider Full-Text Search for word-oriented or unstructured text searches.
  • Use ESCAPE when user input must match wildcard characters such as % or _ literally.

Do not concatenate search text into SQL statements. Parameterize the value. This reduces injection risk and keeps the statement shape more stable for analysis and troubleshooting.

When a function is required, consider a computed column

Sometimes the business rule genuinely requires searching on a transformed value. Instead of repeating the expression in every query, you can expose a computed column:

ALTER TABLE Sales.Customers
ADD NormalizedEmail AS LOWER(LTRIM(RTRIM(EmailAddress))) PERSISTED;

CREATE INDEX IX_Customers_NormalizedEmail
ON Sales.Customers (NormalizedEmail);

This is not an automatic solution for every expression. Indexed computed columns must satisfy SQL Server’s requirements for determinism, precision, data type, ownership, and connection-level SET options. Verify the behavior of collation, NULL values, whitespace, and case handling before adopting the design.

A persisted computed column stores the calculated value and updates it when dependent data changes. That can make indexed access practical, but it also adds storage, write work, and index-maintenance cost. For some systems, normalizing the value during ingestion or storing a dedicated search key is simpler. Choose based on measured workload rather than on the presence of a single slow query.

Use filtered indexes for small, frequently queried subsets

If only a small portion of a table is queried frequently, a filtered index may be more appropriate than a full-table index:

CREATE INDEX IX_Orders_OpenByCustomer
ON Sales.Orders (CustomerId, CreatedAt)
INCLUDE (OrderStatus)
WHERE OrderStatus = 'Open';

Filtered indexes are defined on one table and use simple comparison predicates. The query predicate must be compatible with the filter so that the optimizer can establish that the index contains the required rows. Filtered indexes can reduce storage and maintenance compared with indexing the entire table, but their usefulness depends on stable data distribution and recurring query shapes.

How to validate the change

  1. Capture the actual workload: parameter values, returned row counts, duration, and execution frequency.
  2. Inspect the actual execution plan and compare estimated versus actual rows near the access and filter operators.
  3. Use SET STATISTICS IO, TIME ON in a controlled test to measure logical reads and CPU time.
  4. Run both the original and revised predicates with representative and boundary parameter values.
  5. Review existing indexes before adding another one; a covering index may already exist with a different key order.

An index seek is not automatically a success. A seek can still read a very wide range. Likewise, an index scan can be the correct choice for a small table or a query returning a large percentage of rows. Measure logical reads, CPU, duration, memory grants, and concurrency impact in the real workload.

Practical checklist

  • Keep indexed columns free of unnecessary functions and expressions.
  • Use half-open intervals for date and timestamp filtering.
  • Pass parameters using compatible data types.
  • Avoid a leading % in LIKE unless substring matching is required.
  • Use Full-Text Search or a dedicated search service for large-scale text search.
  • Use computed columns or normalized search keys for repeated, deterministic transformations.
  • Consider filtered indexes for selective, stable subsets.
  • Validate every change with actual plans, logical reads, representative parameters, and write overhead.

Sources

//

0 Comments

Write Comment

E-Mail address will not be published