Is concatenated string on where clause SARGable?

依然范特西╮ 提交于 2021-01-28 03:00:43

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/29406797/is-concatenated-string-on-where-clause-sargable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!