TtT23
TtT23

Reputation: 7030

Is concatenated string on where clause SARGable?

Let's say I have a nonclustered index on two nvarchar columns, A and B.

If my query looks something like this:

SELECT Columns FROM Table WHERE A + B = '1234'

Can the query effectively use the index?

Or should I separate the columns in where clause

SELECT Columns FROM Table WHERE A = '12' AND B = '34'

I've found pretty surprising results from my testings. Both produced an identical query plan, but the costs were different. Most of the time, the concatenated query would be faster but from time to time, the separated version would be faster.

Upvotes: 2

Views: 328

Answers (1)

Giorgi Nakeuri
Giorgi Nakeuri

Reputation: 35790

Any expression, function, calculation applied to column breaks SARGability. The main formula looks like:

column operator value or

value operator column.

Column should be just column name. Operator can be =, >, <=, >=, between, like. Value can be constant or any expression. Like should be like like 'AAA%_. If Like is %AAA or _AAA it is not SARGable.

So the answer is: if you can split your predicate to WHERE A = '12' AND B = '34', this will use index if any appropriate exists. This WHERE A + B = '1234' won't use index.

Upvotes: 2

Related Questions