5

I have a general question regarding using String Functions and their impact on performance. I have a table with a non-clustered index on column ID. The column has 20 digit varchar in it. When I run :

SELECT col1, col2 
FROM tbl
WHERE ID = '00000000009123548754' 

The result comes back very fast. But when I run

SELECT col1, col2 
FROM tbl
WHERE RIGHT(ID, 10) = '9123548754'

It takes a very long time. The estimated execution plan for the first query has a Index Seek, where as for the second query is has a Index Scan.

I understand that the Seek as oppose to the Scan is the reason one is faster, but why does the String Function Right() has such an impact?

5
  • If there are 20 digits, then the second will return no rows. Commented Jan 4, 2017 at 0:22
  • 3
    Well, RIGHT() cannot work in conjunction with the hashed values your index is based upon, so it has to evaluate every ID value. Try and run Database Engine Tuning Advisor against your query and see what it comes up with. Commented Jan 4, 2017 at 0:25
  • What version of what database are you using? Commented Jan 4, 2017 at 0:30
  • SQL Server 2005 Commented Jan 4, 2017 at 0:38
  • How many rows are we talking about? Commented Jan 4, 2017 at 11:05

1 Answer 1

4

The reason there is a difference is because the RIGHT(ID,10) has to be resolved for every row in order to filter it (hence the scan), whereas the ID = '00000000009123548754' clause can be resolved to a simple seek.

In technical terms, your first query is sargable, while the second isn't (due to the function).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.