Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating the SQL query plan takes 5 minutes, the query itself runs in milliseconds. What's up?

I have a fairly complex (or ugly depending on how you look at it) stored procedure running on SQL Server 2008. It bases a lot of the logic on a view that has a pk table and a fk table. The fk table is left joined to the pk table slightly more than 30 times (the fk table has a poor design - it uses name value pairs that I need to flatten out. Unfortunately, it's 3rd party and I cannot change it).

Anyway, it had been running fine for weeks until I periodically noticed a run that would take 3-5 minutes. It turns out that this is the time it takes to generate the query plan. Once the query plan exists and is cached, the stored procedure itself runs very efficiently. Things run smoothly until there is a reason to regenerate and cache the query plan again.

Has anyone seen this? Why does it take so long to generate the plan? Are there ways to make it come up with a plan faster?

like image 809
TheEmirOfGroofunkistan Avatar asked Apr 11 '10 00:04

TheEmirOfGroofunkistan


People also ask

How long does it take SQL query to run?

The query takes 20 to 500 ms (or sometimes more) depending on the system and the amount of data. The performance of the database or the database server has a significant influence on the speed. A tip: Test your system using the demo license of the Connector to get an indication of the performance of your components.

How do I find the run time of a query?

Using Client StatisticsGo to Menu >> Query >> Select Include client Statistics. Execute your query. In the results panel, you can see a new tab Client Statistics. Go to the Client Statistics tab to see the execution time.

Why does the same query takes different amount of time to run?

The first time you run your query, data is read from storage. The next time you run that query, a lot of the data and indexes will be cached in memory.

Why does a query run faster the second time?

What you are experiencing is called caching. The database doesn't have to go to disk the 2nd time because it can either get the data from its own buffer cache, or the operating system/disk array can also provide the data faster from its own cache.


1 Answers

You can try using a Plan Guide. Plan generation will still last some time, but should be significantly shorter.

like image 59
Remus Rusanu Avatar answered Oct 06 '22 16:10

Remus Rusanu