Can the row-count fluctuation in a table cause a query to perform slowly?
If a SQL Server table has regular inserts then deletes sometimes and then more inserts causing the total-row count to always change in that table cause a SELECT query to chose different execution plans and cause delays?
I've had situations where my SELECT query has run in 12-14 seconds while sometimes run for 40-240 minutes on a table which has indexes created additionally including the original ones, covering indexes, statistics updated, etc.
As an fyi, the query itself was presented on the forums and shown to multiple senior SQL experts and none found anything exceptional about this simple SELECT query using joins & subqueries in the where clause.
asked Oct 25 '09 at 06:22 PM in Default
Out-of-date statistics can cause the Query Optimizer to make the wrong decision about how to run a query, but the amount of contrast you're describing is certainly extreme. I would recommend forcing a particular plan in this situation. It seems as if you've found one of the bugs in the Query Optimizer.
The other thing that could cause it to be painfully slow could be locking. If the query is hitting an object that is locked by another process (for example, someone's updated some data and hasn't ended the transaction yet), then that could stop the query for a long period. Have you looked into blocking when that query is running? If it's a problem, then consider using snapshot isolation instead, or weighing up the pain of NOLOCK.
answered Oct 25 '09 at 07:27 PM
It could simply be an issue of contention, more then one resource vieing for pages in the table and blocking each other, especially if you're doing that many inserts & deletes. But it's probably statistics. The trick will be to capture the execution plan of the query when it's running slowly and comparing it to when it's running normally. If they're the same, it's probably blocking of some sort.
The way I'd suggest capturing it, since you don't know for sure when it's going to occur, is to query the dynamic management view sys.dm_exec_query_plan.
answered Oct 25 '09 at 10:48 PM
Grant Fritchey ♦♦