2

For a table with a column ColA as VARCHAR(x), how should I rewrite this condition

ColA LIKE @param + '%'

taking into account that:

  • 1/ ColA is NULLable.
  • 2/ @param could be NULL
  • 3/ There is an index on ColA, and it should be used for all searches
  • 4/ Avoid sp_executesql as this is part of much larger stored proc

I was thinking at:

ISNULL(ColA, '') LIKE (CASE WHEN @param IS NULL THEN '%' ELSE @param + '%' END)         

but this will not make use of index defined on ColA.

MPelletier
  • 16,256
  • 15
  • 86
  • 137
user3104183
  • 408
  • 1
  • 9
  • 26

2 Answers2

1

Split into two conditions:

...
WHERE ((@param is null AND ColA is null)
  OR (@param IS NOT NULL AND ColA LIKE @param + '%'))

But OR often kills index usage, so if that doesn't work, try further split into two queries:

...
WHERE @param is null
AND ColA is null
UNION
...
WHERE @param IS NOT NULL
AND ColA LIKE @param + '%'

But

Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • I think the second condition `@param IS NOT NULL` is needless. In case of `@param=NULL` we get `ColA LIKE NULL` and it's always FALSE. – valex Feb 14 '14 at 08:29
  • @valex *logically* it might be unnecessary, but *performance* may be far greater with it in because the entire LIKE search can be avoided when param is null. With the additional test, it may execute the like anyway (depending on optimizer) – Bohemian Feb 14 '14 at 08:43
  • I Agree it depends on optimizer. – valex Feb 14 '14 at 08:52
  • What is I have 2 columns, ColA, ColB, with 2 indexes? – user3104183 Feb 14 '14 at 10:48
  • Do you have a param for each, or do they share the same param? – Bohemian Feb 14 '14 at 10:51
0

Just use:

WHERE ((@param is NULL) and (ColA is NULL)) OR (ColA LIKE '%' + @param + '%')

But if you use LIKE '%' + @param + '%' index can't be used (if it isn't FULL-TEXT index):

- SQL Server Index - Any improvement for LIKE queries?

- Index usage by %Like% operator – Query Tuning

Community
  • 1
  • 1
valex
  • 23,966
  • 7
  • 43
  • 60