Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you fix queries that only run slow until they're cached

I have some queries that are causing timeouts in our live environment. (>30 seconds)

If I run profiler and grab the exact SQL being run and run it from Management Studio then they take a long time to run the first time and then drop to a few hundred miliseconds each run after that.

This is obviously SQL caching the data and getting it all in memory.

I'm sure there are optimisations that can be made to the SQL that will make it run faster.

My question is, how can I "fix" these queries when the second time I run it the data has already been cached and is fast?

like image 444
Robin Day Avatar asked Jan 29 '09 12:01

Robin Day


People also ask

How do you make your queries run faster?

The way to make a query run faster is to reduce the number of calculations that the software (and therefore hardware) must perform. To do this, you'll need some understanding of how SQL actually makes calculations.

What are the most likely causes of slow running queries?

Queries can become slow for various reasons ranging from improper index usage to bugs in the storage engine itself. However, in most cases, queries become slow because developers or MySQL database administrators neglect to monitor them and keep an eye on their performance.


1 Answers

Use can use

DBCC DROPCLEANBUFFERS   
DBCC FREEPROCCACHE

But only use this in your development environment whilst tuning the queries for deployment to a live server.

like image 74
Coolcoder Avatar answered Oct 04 '22 22:10

Coolcoder