What makes a SQL statement sargable? What makes a SQL statement sargable? sql-server sql-server

What makes a SQL statement sargable?


The most common thing that will make a query non-sargable is to include a field inside a function in the where clause:

SELECT ... FROM ...WHERE Year(myDate) = 2008

The SQL optimizer can't use an index on myDate, even if one exists. It will literally have to evaluate this function for every row of the table. Much better to use:

WHERE myDate >= '01-01-2008' AND myDate < '01-01-2009'

Some other examples:

Bad: Select ... WHERE isNull(FullName,'Ed Jones') = 'Ed Jones'Fixed: Select ... WHERE ((FullName = 'Ed Jones') OR (FullName IS NULL))Bad: Select ... WHERE SUBSTRING(DealerName,4) = 'Ford'Fixed: Select ... WHERE DealerName Like 'Ford%'Bad: Select ... WHERE DateDiff(mm,OrderDate,GetDate()) >= 30Fixed: Select ... WHERE OrderDate < DateAdd(mm,-30,GetDate()) 


Don't do this:

WHERE Field LIKE '%blah%'

That causes a table/index scan, because the LIKE value begins with a wildcard character.

Don't do this:

WHERE FUNCTION(Field) = 'BLAH'

That causes a table/index scan.

The database server will have to evaluate FUNCTION() against every row in the table and then compare it to 'BLAH'.

If possible, do it in reverse:

WHERE Field = INVERSE_FUNCTION('BLAH')

This will run INVERSE_FUNCTION() against the parameter once and will still allow use of the index.


In this answer I assume the database has sufficient covering indexes. There are enough questions about this topic.

A lot of the times the sargability of a query is determined by the tipping point of the related indexes. The tipping point defines the difference between seeking and scanning an index while joining one table or result set onto another. One seek is of course much faster than scanning a whole table, but when you have to seek a lot of rows, a scan could make more sense.

So among other things a SQL statement is more sargable when the optimizer expects the number of resulting rows of one table to be less than the tipping point of a possible index on the next table.

You can find a detailed post and example here.