老外提问:

Hi, I have an sql query which takes 8 seconds in the first run. The next run there after takes 0.5 seconds and all consecutive runs take 0.5 seconds. Is the plan getting cached? How do i make this query run in 0.5 second in the first run itself? Please find the query below.

select isnull(joblabor.IDNumber,-1) 'ProcessTransactionID',EmpNo 'EmployeeID',case(joblabor.lJob) when '-1' then '' else joblabor.ljob end 'JobID',
joblabor.ProcNo 'ActivityID',process.Process 'ActvityName', joblabor.shift 'Shift',case (isnull(suspend,0)) when 1 then 'true' else 'false' end 'Suspended',
joblabor.StartTime 'StartDateTime',joblabor.starttime 'StartTime', joblabor.updated 'UpdatedDate',
ProcQuant 'Quantity',Prochours 'Hours',isnull(Remarks,'') 'Remark',IsNull(JCNotes,'') 'Notes',IsNULL(JobFormSpecs.PartDes,'') as FormDesc,
IsNull(Job.EstDes1,'') 'JobDesc',0 'Standard',0 'MinimumStd',0 'MaximumStd',JobLabor.PartNo 'FormID',joblabor.CostDate 'CostDate',isnull(JobLabor.linenum,1) 'ProcessTransactionIndex',case(joblabor.suspend) when 1 then 1 else 0 end 'ProcessType'
,(joblabor.timepct*100) 'Percent',IsNull(Job.FCustNo,'') 'CustomerID', IsNull(Job.FCompany,'') 'CustomerName' , joblabor.EndTime 'EndDateTime',process.ProcGroup 'ActivityGroup',
case (LEN(LTRIM(SUBSTRING(Job.remark1, 1, 25)))) when 0 then 'false' else 'true' end 'HasJobNotes' ,
case (isnull(ProcessRemarks.ContainsProcessRemarks,0)) when 0 then 'false' else 'true' end 'HasProcessRemarks' ,
case (isnull(ChangeOrder.ContainsChangeOrders,0)) when 0 then 'false' else 'true' end 'HasAlteration'
,isnull(joblabor.costcode,'') 'CostStatus'
,isnull(Complete,'') 'CompletionCode',GRYield 'GrossYield',NetYield 'NetYield'
from BBJobCST joblabor (nolock)
Left Outer Join bbjthead Job (nolock) on (joblabor.lJob = Job.lJob)
inner join SSProces as Process (nolock) on( process.ProcNo = joblabor.ProcNo AND process.archive = 0)
left outer join bbPthead JobFormSpecs (nolock) on (ltrim(rtrim(joblabor.Ljob)) = ltrim(rtrim(JobFormSpecs.LJob)) and ltrim(rtrim(JobLabor.PartNo))=ltrim(rtrim(jobFormSpecs.PartNo)) )
left outer join (
SELECT Count(bbchghdr.ljob) 'ContainsChangeOrders', bbchghdr.ljob FROM bbchghdr (nolock)
inner join bbchglin (nolock) ON bbchghdr.ljob = bbchglin.ljob AND bbchghdr.changeno = bbchglin.changeno
WHERE type = 'P' AND descript NOT LIKE '' group by bbchghdr.ljob) ChangeOrder on ChangeOrder.ljob=joblabor.ljob
left join (
SELECT Count(bbjobcst.ljob) 'ContainsProcessRemarks', bbjobcst.ljob
FROM bbjobcst (nolock) WHERE ( LEN(LTRIM(SUBSTRING(bbjobcst.jcnotes, 1, 25))) > 0 or LEN(LTRIM(remarks)) > 0)
Group By bbjobcst.ljob) ProcessRemarks on ProcessRemarks.ljob=joblabor.ljob
where joblabor.empno = '' and
(isnull(joblabor.endtime,'') = '' or suspend=1 ) and (joblabor.ProcHours = 0 or suspend=1 )
and joblabor.ljob <> 0
order by joblabor.Costdate desc,joblabor.starttime desc,[linenum] asc

Thanks in advance.

回答:

It isn’t the query plan that is getting cached – it is the actual data and indexes which are being cached.  This is common behavior of any database. If you ran the query, then waited a while and ran again (keeping the session active), you would see the query take longer again, based on the cached data/indexes being flushed to make room for other data.

You can see if you can reduce the 0.5 seconds repeat time, and/or you can see if you can reduce the intermediate result sets (which are usually what get cached and speed up the queries the second..nth runs).

If the query is producing a large intermediate result set (perhaps a large join where most records are then discarded), you may be able to speed it up by changing parts of your query.  Also, sometimes just adding the right index can solve issues like this.

Look at the execution plan and see if there are any “table access full”, “index access full”, “cartesian”, or similar joins indicating inefficient join/indexing.

意思就是说Sql语句第一次查询慢的原因不仅仅是因为执行计划没有被缓存这么简单,有时候你会发现Sql语句重用了执行计划,但是第一次查询还是很慢。就如同上面回答一样,最主要的原因是第一次查询的时候,Sql Server会将查询出的部分数据和索引从磁盘加载到内存作为缓存,而第二次查询的时候就直接从内存缓存中拿出数据了,自然要比从磁盘上加载数据快很多,Sql Server会定期清除缓存,所以一段Sql语句如果长期不执行后,就需要从磁盘从新加载数据。

原文链接

为什么Sql Server的查询有时候第一次执行很慢,第二次,第三次执行就变快了的更多相关文章

  1. CASE函数 sql server——分组查询(方法和思想) ref和out 一般处理程序结合反射技术统一执行客户端请求 遍历查询结果集,update数据 HBuilder设置APP状态栏

    CASE函数   作用: 可以将查询结果集的某一列的字段值进行替换 它可以生成一个新列 相当于switch...case和 if..else 使用语法: case 表达式/字段 when 值 then ...

  2. C#构造方法(函数) C#方法重载 C#字段和属性 MUI实现上拉加载和下拉刷新 SVN常用功能介绍(二) SVN常用功能介绍(一) ASP.NET常用内置对象之——Server sql server——子查询 C#接口 字符串的本质 AJAX原生JavaScript写法

    C#构造方法(函数)   一.概括 1.通常创建一个对象的方法如图: 通过  Student tom = new Student(); 创建tom对象,这种创建实例的形式被称为构造方法. 简述:用来初 ...

  3. Sql Server参数化查询之where in和like实现详解

    where in 的参数化查询实现 首先说一下我们常用的办法,直接拼SQL实现,一般情况下都能满足需要 string userIds = "1,2,3,4"; using (Sql ...

  4. 【转】Sql Server参数化查询之where in和like实现之xml和DataTable传参

    转载至: http://www.cnblogs.com/lzrabbit/archive/2012/04/29/2475427.html 在上一篇Sql Server参数化查询之where in和li ...

  5. 【转】Sql Server参数化查询之where in和like实现详解

    转载至:http://www.cnblogs.com/lzrabbit/archive/2012/04/22/2465313.html 文章导读 拼SQL实现where in查询 使用CHARINDE ...

  6. 优化SQL Server数据库查询方法

    SQL Server数据库查询速度慢的原因有很多,常见的有以下几种: 1.没有索引或者没有用到索引(这是查询慢最常见的问题,是程序设计的缺陷) 2.I/O吞吐量小,形成了瓶颈效应. 3.没有创建计算列 ...

  7. 转载 50种方法优化SQL Server数据库查询

    原文地址 http://www.cnblogs.com/zhycyq/articles/2636748.html 50种方法优化SQL Server数据库查询 查询速度慢的原因很多,常见如下几种: 1 ...

  8. SQL Server 2016 查询存储性能优化小结

    SQL Server 2016已经发布了有半年多,相信还有很多小伙伴还没有开始使用,今天我们来谈谈SQL Server 2016 查询存储性能优化,希望大家能够喜欢 作为一个DBA,排除SQL Ser ...

  9. 【转载】Sql Server参数化查询之where in和like实现详解

    文章导读 拼SQL实现where in查询 使用CHARINDEX或like实现where in 参数化 使用exec动态执行SQl实现where in 参数化 为每一个参数生成一个参数实现where ...

随机推荐

  1. 什么是MSI文件?

    当你双击`msi`文件时,就会调用`window.installer`程序,接下来就和安装其他程序一样了,但是你要确保你的`window.installer`服务是开启的,你可以在控制面板下的服务中找 ...

  2. redisTemplate实现轻量级消息队列, 异步处理excel并实现腾讯云cos文件上传下载

    背景 公司项目有个需求, 前端上传excel文件, 后端读取数据.处理数据.返回错误数据, 最简单的方式同步处理, 客户端上传文件后一直阻塞等待响应, 但用户体验无疑很差, 处理数据可能十分耗时, 没 ...

  3. linux buff/cache释放

    手动释放cache # > /proc/sys/vm/drop_caches

  4. C/C++求职宝典21个重点笔记(常考笔试面试点)

    这是我之前准备找工作时看<C/C++求职宝典>一书做的笔记,都是一些笔试面试中常考的重点难点问题,但比较基础,适合初学者看. 1. char c = '\72'; 中的\72代表一个字符, ...

  5. Ceph/共享存储 汇总

    Ceph 存储集群 - 搭建存储集群 Ceph 存储集群 - 存储池 Ceph 块设备 - 命令,快照,镜像 Ceph 块设备 - 块设备快速入门 OpenStack 对接 Ceph CentOS7 ...

  6. Tomcat学习总结(8)——Tomcat+Nginx集群解决均衡负载及生产环境热部署

    近日,为解决生产环境热部署问题,决定在服务器中增加一个tomcat组成集群,利用集群解决热部署问题. 这样既能解决高并发瓶颈问题,又能解决热部署(不影响用户使用的情况下平滑更新生产服务器)问题. 因为 ...

  7. Apache 源码安装

    8.20]# make[root@yahoo pcre-8.20]# make install 二.安装apache1.下载httpd-2.4.3.tar.gz,地址是:http://httpd.ap ...

  8. Python后端相关技术/工具栈

    编辑器 最常见: vim / SublimeText2 / PyCharm Vim有兴趣可以看看 k-vim 适合Python/Golang开发 本地环境 pip/easy_install 包管理 v ...

  9. 第一次项目上Linux服务器(一:远程连接服务器)

    一.准备工作 1.Linux服务器一台,以及服务器ip.用户名.密码 2.安装xfttp和xshell软件,资源链接,百度云链接:https://pan.baidu.com/s/1vwnlbBpmjX ...

  10. 【webserver】使用python实现webserver,支持上传下载文件

    #!/usr/bin/env python """Simple HTTP Server With Upload. This module builds on BaseHT ...