views:

49

answers:

1

Hello everyone,

I am using SQL Server 2008 Enterprise. Now I have two patterns to implement the same function (to see if zoo1 or zoo2 or zoo3 column contains some text, in pattern 1, I merge content of zoo1, zoo2 and zoo3 to form a new column called zoo), I think the first pattern is always of better performance (I have made some experiment) from my experiment. But I am not sure whether I am correct, and what is the internal reason why pattern 1 is always of better performance?

Pattern 1:

Select foo, goo from tablefoo where zoo like LIKE '%'+@Query+'%'

Pattern 2 (zoo is a column which I merge the content of column zoo1, zoo2 and zoo3 to generate):

Select foo, goo from tablefoo where (zoo1 like LIKE '%'+@Query+'%') OR (zoo2 like LIKE '%'+@Query+'%') or (zoo3 like LIKE '%'+@Query+'%')

thanks in advance, George

+3  A: 

OR almost always kills performance.

In this case, it's 3 columns to scan vs 1 column to scan.

In both cases, because you have a leading % then an index won't be used anyway (it may be scan because it's covers the zoo% columns)

The 1 column is merely less bad than the 3 column OR query. Not "better".

gbn
So, conclusion is a little improvement of using no OR?
George2
@George: in this case, yes. In other cases, it probably would be better
gbn
Using leading % is not using index, why?
George2
@George: Indexes are sorted by the key value(s) and an index seek takes advantage of the sort sequence to find the data. For example, if 'Zoo%' is greater than 'M', SQL Server doesn't have to look at values less than or equal to 'M'. By putting a leading %, you're telling SQL Server to find values that begin with 'A' or 'Z', or any valid character. SQL Server must check all values, which defeats the advantage of the index.
bobs
@bobs: excellent description!
gbn
Thanks, question answered!
George2