Why is my Sql Query is Faster the Second Time it Runs? - sql-server

Every time I am getting same execution time while executing the SQL query.
is there any chance to get same execution time for all the time if SQL query runs multiple times?

When you run your query for the first time and the data is not in cache, the server read the data from disk. It is time-comsuming. The second time you execute the same query data is already in cache so it requires less time.
is there any chance to get same execution time for all the time if SQL
query runs multiple times ?
If you want to test your queries with the cold cache (with no data cached, every time) you can use DBCC DROPCLEANBUFFERS before your query execution:
Use DBCC DROPCLEANBUFFERS to test queries with a cold buffer cache
without shutting down and restarting the server. To drop clean buffers
from the buffer pool and columnstore objects from the columnstore
object pool, first use CHECKPOINT to produce a cold buffer cache. This
forces all dirty pages for the current database to be written to disk
and cleans the buffers. After you do this, you can issue DBCC
DROPCLEANBUFFERS command to remove all buffers from the buffer pool.
Of course this is not to be used in production environment.
If
conversely you want to have your data always in cache, you should increase RAM for your server and don't restart it as long as possible.

Related

How to clear sqlserver cache to get correct execution plan

I had a query that was running slow (2.5 mins) on sqlserver.
I got actual execution plan, and there was a suggestion for an index. I created the index and now execution time is < 2 seconds.
Then we had to restart sql server.
Query went back to being slow (2.5 mins), again, I looked at execution plan. This time there was a suggestion for a different index!
It would appear that first execution plan index suggestion was taking into account some sort of cached index maybe?
How can I clear cache (if this is the issue) before looking at execution plan?
The symptoms suggest parameter sniffing, where the query plan was generated for the initially supplied parameter values but the plan is suboptimal for subsequent queries with different values. You can invalidate the currently cached plan for specific query by providing the plan handle to DBCC FREEPROCCACHE:
DBCC FREEPROCCACHE(plan_pandle);
There are a number of ways to avoid parameter sniffing. If the query is not executed frequently, a recompile query hint will provide the optimal plan for the parameter values supplied. Otherwise, you could specify an optimize for unknown hint or use the Query Store (depending on your SQL Server version) to force a specific plan or have SQL Server automatically identify plan regression and select a plan.
Dont clear the cache in PRODUCTION environment. It will lead to serious performance issues.
If you want to generate new plan instead of existing plan, you can go for RECOMPILE option as part of stored procedure execution to see whether new index is being considered in the new plan.
EXEC dbo.Procedure WITH RECOMPILE;
or you can regenerate the execution plan for the procedure, by using the below command. Next time, it will be using the newly generated plan.
EXEC sp_recompile `dbo.procedure`
If you want to measure performance improvement repeatedly in a test environment, you can go with below clearing approaches:
DBCC FREEPROCCACHE -- It will clear the plan cache completely
DBCC DROPCLEANBUFFERS -- It will clear the unchanged data brought from disk to memory.
More elegant approach is to write the dirty pages to disk and then issue the cleaning of unchanged data.
CHECKPOINT;
GO
DBCC DROPCLEANBUFFERS;
GO
DBCC FREEPROCCACHE;
GO

Stored Procedure is faster the 2nd time

I am running SP on SQL Server 2017
The first time I executed the SP it took 43 sec
but the 2nd time it took 1 sec only
How can I execute the SP everytime same as the first time without cache or any learning from the previous experience?
I am not asking why, as this question wants to know Why this is happening
First run slowness in a sql server stored procedure
I am asking, How to make it the same as the first time.
I want my procedure everytime it executes as if its the first time
If you want to remove stored plan caches, you can execute DBCC FREEPROCCACHE. Just beware that it will get a clean slate for all stored procedures.
Remember that once the plan is compiled, it will be stored for future calls until either the SP gets altered or a dependent object is also modified. So most of the times what you want to test is actually the performance of the already compiled plan, unless you constantly are clearing these caches, restarting the servers or triggering a recompile somehow.
Run:
CHECKPOINT;
DBCC DROPCLEANBUFFERS;
prior to each execution. This will clear the buffer pool so that the playing field is leveled and each iteration will incur roughly the same IO overhead.
Also see Performance testing with DBCC DROPCLEANBUFFERS for additional considerations for measuring performance with this method.

Query terrible slow after DBCC DROPCLEANBUFFERS / FREEPROCCACHE

I have a complex query that runs under 2 seconds (which is ok), however if i run
DBCC DROPCLEANBUFFERS
DBCC FREEPROCCACHE
first the query performans goes oder 40 seconds. Should I be worried?
No, Sql server is doing EXACTLY what you just told it to. You asked it to empty out ALL it's hard earned buffers.
It ran first previously because it had stored the information about the tables and the query in the caches and deleted the execution plans. Having purged them it has to rebuild them from scratch.
Don't do that unless you've a good reason to.
Use DBCC FREEPROCCACHE to clear the plan cache carefully. Freeing the plan cache causes, for example, a stored procedure to be recompiled instead of reused from the cache. This can cause a sudden, temporary decrease in query performance. For each cleared cachestore in the plan cache, the SQL Server error log will contain the following informational message: "SQL Server has encountered %d occurrence(s) of cachestore flush for the ‘%s’ cachestore (part of plan cache) due to ‘DBCC FREEPROCCACHE’ or ‘DBCC FREESYSTEMCACHE’ operations." This message is logged every five minutes as long as the cache is flushed within that time interval.
Use DBCC DROPCLEANBUFFERS to test queries with a cold buffer cache without shutting down and restarting the server.
To drop clean buffers from the buffer pool, first use CHECKPOINT to produce a cold buffer cache. This forces all dirty pages for the current database to be written to disk and cleans the buffers. After you do this, you can issue DBCC DROPCLEANBUFFERS command to remove all buffers from the buffer pool.

SQL Server : same query running multiple times with different execution time

I have a very simple query
SELECT count(*) FROM MyTable
There are 508,000 rows in it. When I run the above query for the very first time it takes approximately 53 seconds to return the result. If I rerun the query again, it takes milliseconds to return the result.
I believe SQL Server is caching the query/results? Is it possible that I could tell SQL Server not to cache query/results, or somehow clear the cache/result?
In my application I am trying to do some performance tuning, but problems like above don't help me out.
Yes, you can flush the data buffer like this (but seriously, don't!):
DBCC DROPCLEANBUFFERS
Use DBCC DROPCLEANBUFFERS to test queries with a cold buffer cache
without shutting down and restarting the server.
To drop clean buffers from the buffer pool, first use CHECKPOINT to
produce a cold buffer cache. This forces all dirty pages for the
current database to be written to disk and cleans the buffers. After
you do this, you can issue DBCC DROPCLEANBUFFERS command to remove all
buffers from the buffer pool.
Ref
You have already ruled out the database as your bottleneck (which it is often), so rather than freeing the data buffer cache, I suggest you profile your code.

How to bypass SQL Server caching

When I am trying to examine the performance of a given query in my application I'm generally uninterested in the effect my code is having. I want to be able to watch the time taken in Sql Management Studio.
Unfortunately, I'm finding that some sort of caching must be going on, because one query that returns 10,000 results from a table with 26 or so columns, many of them large varchars, takes 12 seconds the first time I run it in a while and takes 6 seconds the following times unless I don't re-run it for a few minutes.
Is there any way to instruct it to bypass the cache and pretend like it had never run it before? I'm using SQL Server 10.0.
You can clean out the cache and sproc cache with
DBCC DROPCLEANBUFFERS
DBCC FREEPROCCACHE
respectively

Resources