热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

sql查询性能优化

本文由编程笔记#小编为大家整理,主要介绍了sql查询性能优化相关的知识,希望对你有一定的参考价值。
本文由编程笔记#小编为大家整理,主要介绍了sql 查询性能优化相关的知识,希望对你有一定的参考价值。




/**************************
SEARCH ARGUMENT ABLE QUERIES (SARGABLE)
***************************/
/*
SARGable is defined as “In relational databases, a condition (or predicate) in a query is said to
be sargable if the DBMS engine can take advantage of an index to speed up the execution of the query.
The term is derived from a contraction of Search ARGument ABLE”
Sargable queries are those which are able to use created indexes on them for faster searches and
execution of a query. A faster search means making an effective index seek out large numbers of
rows and avoiding costly index scans.
*Index Seek* – queries are able to use indexes effectively and locate rows with less effort from the
query optimizer.
*Index Scan* – scanning the entire table to locate rows to satisfy the search
criteria.
What Makes a Query Non-Sargable (not able to use created indexes effectively)?
1. using functions in Where clause conditions (because a function is evaluated against each row which
forces the query optimizer not to use the index)
2. using LIKE ‘%Proposal%’ in Wild card search queries
3. performing arithmetic calculation on an index column in a Where clause
Here are some main situations that lead to non-sargable queries, and how you can avoid them:
*/
-- 1. USING A FUNCITON IN WHERE CLAUSE TO SEARCH A STRING
--Non-sargable query because of function Used in WHERE clause
SELECT EmployeeName
FROM EmployeeTest
WHERE LEFT( EmployeeName,1 ) = 'A';
--Better sargable query that instead uses LIKE with a prefix (ie no wildcard at beginning of LIKE - '%A%')
SELECT EmployeeName
FROM EmployeeTest
WHERE EmployeeName LIKE 'A%';
-- 2. USING A FUNCITON IN WHERE CLAUSE TO SEARCH A DATE COLUMN
--Non-sargable query because of function used in WHERE clause
SELECT DateOfBirth
FROM EmployeeTest
WHERE YEAR (DateOfBirth) = '1952';
--Better sargable query that doesn't use function and instead searches within a consecutive range
SELECT DateOfBirth
FROM EmployeeTest
WHERE DateOfBirth >= &#39;19520101&#39; AND DateOfBirth <&#39;19530101&#39;;
-- 3. USING CALCULATIONS IN THE WHERE CLAUSE
--Non-sargable query because of calculation done on index column in WHERE clause
SELECT Salary
FROM EmployeeTest
WHERE Salary / 2 = 50147 ;
--Better, sargable query where calculation is done separately and then evaluated against index column
--(instead of actually calculating against the index column, which would manipulate that column
--and make it so SQL Server can&#39;t trust the order of the index)
SELECT Salary
FROM EmployeeTest
WHERE Salary = (50147 * 2);
-- 4. USING ISNULL() IN THE WHERE CLAUSE
--Non-sargable query because of ISNULL function on Index Column in WHERE Clause
SELECT EmployeeName
FROM EmployeeTest
where ISNULL (EmployeeName, &#39;Vru&#39;) = &#39;Vru&#39; ;
--Better, sargable query that doesn&#39;t use funciton and instead uses OR to test if row IS NULL
SELECT EmployeeName
FROM EmployeeTest
where EmployeeName = &#39;Vru&#39; OR EmployeeName IS NULL;
/**************************
SUBQUERY VS JOIN PERFORMANCE
***************************/
/*
Correlated subqueries and JOINs can return the same results. Sometimes subqueries will work better
than JOINs in terms of performance, and sometimes the other way around. You can figure out which works
better in certain instances by trying both methods in the same batch, and looking at the execution plan
to see what percentage of the work was consumed by each method. The method that used less of a percentage
will be the more efficient method.
As an example as to situations where JOINs perform better, for subqueries that need to apply computations
such as aggregates based on teh same set of rows, SQL Server will performan a separate access to the data
for each subquery. With a JOIN, you can apply multiple aggregate calucaltions based on the same access to
the data, and therefore the JOIN will be more efficient.
*/
-- Less efficient SUBQUERY example of multiple aggregate calculations being applied to the same rows
SELECT appeal_no
, campaign_no
, description
, total_tck_income
, total_tck_income / (SELECT sum(b.total_tck_income) FROM T_APPEAL as b WHERE b.campaign_no = a.campaign_no) AS PercentIncome -- correlated subquery, acting on same rows
, total_tck_income - (SELECT avg(c.total_tck_income) FROM T_APPEAL as c WHERE c.campaign_no = a.campaign_no) AS DiffFromAverage -- second correlated subquery, acting on same rows
FROM T_APPEAL AS a
WHERE total_tck_income <> 0
ORDER by campaign_no
-- More efficient JOIN example of the same query where multiple aggregate calculations are applied to the same rows
SELECT a.appeal_no
, a.campaign_no
, a.description
, a.total_tck_income
, total_tck_income / totalticket AS PercentIncome
, total_tck_income - averageticket AS DiffFromAverage
FROM T_APPEAL a
JOIN (SELECT campaign_no, SUM(total_tck_income) AS totalticket -- JOIN using subquery
, AVG(total_tck_income) as averageticket
FROM T_APPEAL GROUP by campaign_no) as b
ON a.campaign_no = b.campaign_no
WHERE total_tck_income <> 0
ORDER by campaign_no
/*
As an example of when a subquery will be more optimal than a JOIN, consider an example where you want
to pull all customers who do not have a contribution. The important index is the customer_no index in T_CUSTOMER.
The reason the subquery below is more efficient is due to the nuance of the optimzier. The bottom line
is that you should test the subquery method vs. the JOIN method to see which functions more efficiently
before putting into production.
*/
-- More efficient subquery method
SELECT * from T_CUSTOMER a
WHERE NOT EXISTS -- where NOT EXISTS the customer_no being in T_CONTRIBUTION
(SELECT * from T_CONTRIBUTION b WHERE a.customer_no = b.customer_no)
-- Less efficient JOIN method that returns the same results
SELECT a.customer_no from T_CUSTOMER a
LEFT JOIN T_CONTRIBUTION b on a.customer_no = b.customer_no
WHERE b.ref_no IS NULL -- similar to the NOT EXISTS from subquery example above
/**************************
TABLE EXPRESSIONS VS. TEMPORARY TABLE VS. TABLE VARIABLE PERFORMANCE
***************************/
/*
There are cases where a table expression is more optimal than a temporary table. This is the case
when you need to query the results only once - it doesn&#39;t make sense to waste the resources to persist
the results to a table when you&#39;re only using it once.
Temporary tables often have better performance when you have a starting table result that you need
to access repeated times, especially if it&#39;s a large or expensive result. If you use a derived
table and reference it multiple times in the outer query, the work is repeated each time. Therefore,
if you have an expensive inner query, it&#39;s best to instead persist this result to a temporary table,
and then reference the temporary table as many times as you need. Each time you reference the
temporary table, you will not be regenerating the result each time as you would be if you
used a dereived table.
The difference between a temporary table and a table variable is that SQL SERVER maintains full
statistics on temporary tables, but does not on table variables. Therefore, cardinality
estimates (estimates for row counts) tend to be more accurate with temporary tables. Therfore the
recommendation is that with small amounts of data with just a few rows, use table variables. With
larger tables sizes, the recommendation is to use temporary tables.
*/


推荐阅读
  • 利用Visual Basic开发SAP接口程序初探的方法与原理
    本文介绍了利用Visual Basic开发SAP接口程序的方法与原理,以及SAP R/3系统的特点和二次开发平台ABAP的使用。通过程序接口自动读取SAP R/3的数据表或视图,在外部进行处理和利用水晶报表等工具生成符合中国人习惯的报表样式。具体介绍了RFC调用的原理和模型,并强调本文主要不讨论SAP R/3函数的开发,而是针对使用SAP的公司的非ABAP开发人员提供了初步的接口程序开发指导。 ... [详细]
  • 从零学Java(10)之方法详解,喷打野你真的没我6!
    本文介绍了从零学Java系列中的第10篇文章,详解了Java中的方法。同时讨论了打野过程中喷打野的影响,以及金色打野刀对经济的增加和线上队友经济的影响。指出喷打野会导致线上经济的消减和影响队伍的团结。 ... [详细]
  • 第七课主要内容:多进程多线程FIFO,LIFO,优先队列线程局部变量进程与线程的选择线程池异步IO概念及twisted案例股票数据抓取 ... [详细]
  • 本文介绍了闭包的定义和运转机制,重点解释了闭包如何能够接触外部函数的作用域中的变量。通过词法作用域的查找规则,闭包可以访问外部函数的作用域。同时还提到了闭包的作用和影响。 ... [详细]
  • Nginx使用(server参数配置)
    本文介绍了Nginx的使用,重点讲解了server参数配置,包括端口号、主机名、根目录等内容。同时,还介绍了Nginx的反向代理功能。 ... [详细]
  • 目录实现效果:实现环境实现方法一:基本思路主要代码JavaScript代码总结方法二主要代码总结方法三基本思路主要代码JavaScriptHTML总结实 ... [详细]
  • 如何使用Java获取服务器硬件信息和磁盘负载率
    本文介绍了使用Java编程语言获取服务器硬件信息和磁盘负载率的方法。首先在远程服务器上搭建一个支持服务端语言的HTTP服务,并获取服务器的磁盘信息,并将结果输出。然后在本地使用JS编写一个AJAX脚本,远程请求服务端的程序,得到结果并展示给用户。其中还介绍了如何提取硬盘序列号的方法。 ... [详细]
  • Voicewo在线语音识别转换jQuery插件的特点和示例
    本文介绍了一款名为Voicewo的在线语音识别转换jQuery插件,该插件具有快速、架构、风格、扩展和兼容等特点,适合在互联网应用中使用。同时还提供了一个快速示例供开发人员参考。 ... [详细]
  • C++中的三角函数计算及其应用
    本文介绍了C++中的三角函数的计算方法和应用,包括计算余弦、正弦、正切值以及反三角函数求对应的弧度制角度的示例代码。代码中使用了C++的数学库和命名空间,通过赋值和输出语句实现了三角函数的计算和结果显示。通过学习本文,读者可以了解到C++中三角函数的基本用法和应用场景。 ... [详细]
  • ASP.NET2.0数据教程之十四:使用FormView的模板
    本文介绍了在ASP.NET 2.0中使用FormView控件来实现自定义的显示外观,与GridView和DetailsView不同,FormView使用模板来呈现,可以实现不规则的外观呈现。同时还介绍了TemplateField的用法和FormView与DetailsView的区别。 ... [详细]
  • VueCLI多页分目录打包的步骤记录
    本文介绍了使用VueCLI进行多页分目录打包的步骤,包括页面目录结构、安装依赖、获取Vue CLI需要的多页对象等内容。同时还提供了自定义不同模块页面标题的方法。 ... [详细]
  • java程序设计试题_《Java语言程序设计》期末考试模拟试题——填空题和编程题...
    一、根据题意,填写出空格中的内容Java平台包括三个技术方向,其中J2ME代表____________、J2SE代表___________、J2EE代表 ... [详细]
  • fileuploadJS@sectionscripts{<scriptsrc~Contentjsfileuploadvendorjquery.ui.widget.js ... [详细]
  • 渗透测试基础bypass绕过阻挡我们的WAF(下)
    渗透测试基础-bypass ... [详细]
  • .NET中各种数据库连接大全(转)[more].NET中各种数据库连接大全sql.gif)SQLSERVEROdbCStandardSecurity:driver{SQLSe ... [详细]
author-avatar
mobiledu2502915233
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有