Is CASE..WHEN..THEN sargable ?

Miguel Gavinhos 216 Reputation points
2022-08-09T09:54:49.947+00:00

Hi!
The big question is case sargable ?
If not is there any workaround to make it sargable ?

Query A:

select * from [dbo].[Mobile]  
where((  
CASE   
When ([MobileNumber] = '123456789') THEN cast(1 as bit)  
END  
) = 1)   

I'm doing case in where statement because I have complex business logic.
This query gets an index scan and 199 logical reads. It looks that is not sargable.

Query B:

select * from [dbo].[Mobile]  
where [MobileNumber] = '123456789'  

This query gets an index seek and 122 logical reads it looks sargable.

Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,640 questions
0 comments No comments
{count} vote

2 answers

Sort by: Most helpful
  1. Erland Sommarskog 111.8K Reputation points MVP
    2022-08-09T21:51:46.407+00:00

    Correct. CASE expressions are not sargable. Very few expressions where an indexed column is entangled of in an expression of any sort can lead to Index Seek.

    1 person found this answer helpful.

  2. Isabellaz-1451 3,616 Reputation points
    2022-08-10T03:16:57.72+00:00

    Hi @Miguel Gavinhos

    Like erland said,SQL Server is very strict about using Index Seek.
    Even below code also can't lead to Index Seek.

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

    Reference thread: https://stackoverflow.com/questions/799584/what-makes-a-sql-statement-sargable

    A Search ARgument ABLE predicate is one where SQL SERVER can utilize an index seek operation, if an index exists.

    A SARGable predicate is one where SQL server can isolate the single value or range of index key values to process

    SARGable predicates include the following operators: =, >, >=, <, <=, IN, BETWEEN, and LIKE (in the case of prefix matching)

    Non-SARGable operators include: NOT, NOT IN, <>, and LIKE (not prefix matching), as well as the use of functions or calculations against the table, and type conversions where the datatype does not fulfill the index created.

    Reference thread:https://dba.stackexchange.com/questions/162263/what-does-the-word-sargable-really-mean

    Best Regards,
    Isabella

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.