I have this stored procedure in my database:
ALTER PROCEDURE [dbo].[sp_FTSearchLocation]
@SearchFor nvarchar(200) = null
,@StartRow int
,@EndRow int
AS
BEGIN
SET NOCOUNT ON;
SELECT * FROM (
SELECT TOP (@EndRow)
*, ROW_NUMBER() OVER (ORDER BY Recommendations DESC, CompanyName) AS num
FROM
dbo.cachedSearchTable
WHERE
(
(@SearchFor IS NULL)
OR (CompanyName like '%' + @SearchFor + '%')
OR (Handle like '%' + @SearchFor + '%')
OR (Activity like '%' + @SearchFor + '%')
)
) As a
WHERE num > @StartRow
OPTION (RECOMPILE)
END
dbo.cachedSearchTable
has a clustered index with the columns Recommendations DESC, CompanyName
. There are no other indexes. I think it is safe to use *
because the table cachedSearchTable
is constructed to only have columns that are relevant to this query.
For some search strings, this procedure runs very fast. For instance, searching for accountants
returns in less than a second. However, others run very slowly: When @SearchFor
is set to soup
it takes about 6 seconds to return.
The execution plans for each of these look the same:
For Accountants
:
ClusteredIndexScan (85%) ->
Segment (15%) ->
ComputeScalar (0%) ->
SequenceProject (0%) ->
Top (0%) ->
Filter (0%) ->
Select (0%).
For Soup
:
ClusteredIndexScan (95%) ->
Parallelism (Gather Streams) (5%) ->
Segment (0%) ->
ComputeScalar (0%) ->
SequenceProject (0%) ->
Top (0%) ->
Filter (0%) ->
Select (0%).
However, for accountants
, the ClusteredIndexScan has an estimated operator cost of 0.57, while for soup
it has a cost of 25.34.
I tried putting 3 non-clustered indexes on the table - one for each of the searched columns - but this did not help.
There are lots of accountants in my database (~4000) and very few with 'soup' in their name (~50). In general, it seems that the query runs fastest when there are lots of possible results to chose from, and slowest when there are very few results to return.
How can I speed up this query? Slowing down the write speed to the table does not matter, but applying more indexes does not seem to help. Can you suggest anything?