0

I have a complex query in .NET. Please see the query (simple query for explanation purposes) below:

SELECT * FROM Person WHERE Name='Ian' AND DateOfBirth='1961-04-04'

and this:

SELECT * FROM Person WHERE Name=@Ian AND DateOfBirth=@DateOfBirth

The table is indexed (name and date of birth).

The first query takes a fraction of a second to run from .NET. The second query takes about 48 seconds. Is this something to do with the execution plan? Is there anything I can do to force SQL Server to recreate the execution plan?

I have seen this question: https://dba.stackexchange.com/questions/530/how-do-you-clear-out-all-old-query-plans-from-within-microsoft-sql-server. However, this is more for stored procedures.

2
  • I'm not sure how you expect us to accurately diagnose the problem when you don't show us real code or code that can reproduce the problem.
    – Becuzz
    Commented Apr 15, 2016 at 13:46
  • @Becuzz, Gordon Lindoff was able to accurately diagnose the problem.
    – w0051977
    Commented Apr 15, 2016 at 14:16

1 Answer 1

5

First, you want a composite index on Person(Name, DateOfBirth), not two indexes (the columns can be in either order).

Second, this probably has to do with the execution plan.

I am going to suggest the RECOMPILE option:

SELECT p.*
FROM Person p
WHERE Name = @Ian AND DateOfBirth = @DateOfBirth
OPTION (RECOMPILE);

What can happen with parameterized queries is that the execution plan is cached the first time it is run -- but that execution plan may not be the best for subsequent invocations.

If that doesn't work, then the problem may be data types, because data type incompatibility can prevent the use of indexes. Be sure that the data types and collations are the same. You might need to cast() the parameters to the appropriate type and/or use COLLATE.

2
  • Thanks for the prompt answer. It has worked. I will mark the answer when it allows me to. +1.
    – w0051977
    Commented Apr 15, 2016 at 13:45
  • You probably don't want the index in either order. Put the most selective index first. Commented Apr 15, 2016 at 14:29

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.