16.1 Introduction to SQL Tuning
Identifying high load or top SQL statements that are responsible for a large share of the application workload and system resources, by reviewing past SQL execution history available in the system
Verifying that the execution plans produced by the query optimizer for these statements perform reasonably
Implementing corrective actions to generate better execution plans for poorly performing SQL statements
OLTP 不推荐使用并行查询 16.3 Identifying High-Load SQL
toad 有工具定义, 排序, 可以看到比较耗费资源的SQL情况
V$SQL view:
V$SQLSTATS : The data in V$SQLSTATS should be ordered by resource usage
V$SQLSTATS.BUFFER_GETS : Buffer gets ( for high CPU using statements)
V$SQLSTATS.DISK_READS: Disk reads (for high I/O statements)
V$SQLSTATS.SORTS : sorts (for many sorts)
SQL Trace : TKPROF 读取 这个 SQL Trace 文件. After you have identified the candidate SQL statements, the next stage is to gather information that is necessary to examine the statements and tune them.
Information to Gather During Tuning
(1) Complete SQL text from V$SQLTEXT
(2) Structure of the tables referenced in the SQL statement, usually by describing the table in SQL*Plus
(3) Definitions of any indexes (columns, column orders), and whether the indexes are unique or non-unique
(4) Optimizer statistics for the segments (including the number of rows each table, selectivity of the index columns), including the date when the segments were last analyzed
(5) Definitions of any views referred to in the SQL statement
(6) Repeat steps two, three, and four for any tables referenced in the view definitions found in step five
(7) Optimizer plan for the SQL statement (either from EXPLAIN PLAN, V$SQL_PLAN, or the TKPROF output)
(8) Any previous optimizer plans for that SQL statement 16.5 Developing Efficient SQL Statements
The query optimizer uses statistics gathered on tables and indexes when determining the optimal execution plan.
If these statistics have not been gathered, or if the statistics are no longer representative of the data stored within the database,
then the optimizer does not have sufficient information to generate the best plan. When tuning (or writing) a SQL statement in an OLTP environment, the goal is to drive from the table that has the most selective filter.
> The driving table has the best filter
> The join order in each step returns the fewest number of rows to the next step (that is, the join order should reflect, where possible, going to the best not-yet-used filters).
> The join method is appropriate for the number of rows being returned. For example, nested loop joins through indexes may not be optimal when the statement returns many rows.
> The database uses views efficiently. Look at the SELECT list to see whether access to the view is necessary.
> There are any unintentional Cartesian products (even with small tables)
> Each table is being accessed efficiently: 16.5.3 Restructuring the SQL Statements 16.5.3.1 Compose Predicates Using AND and =, To improve SQL efficiency, use equijoins whenever possible
16.5.3.2 Avoid Transformed Columns in the WHERE Clause, 例如:
good: WHERE a.order_no = b.order_no
bad: WHERE TO_NUMBER (SUBSTR(a.order_no, INSTR(b.order_no, '.') - 1)) = TO_NUMBER (SUBSTR(a.order_no, INSTR(b.order_no, '.') - 1))
Avoid mixed-mode expressions, and beware of implicit type conversions. When you want to use an index on the VARCHAR2 column charcol, but the WHERE clause looks like this:
AND charcol = numexpr, where numexpr is an expression of number type, Oracle Database translates that expression into: AND TO_NUMBER(charcol) = numexpr
Avoid the following kinds of complex expressions:
col1 = NVL (:b1,col1)
NVL (col1,-999) = ....
TO_DATE(), TO_NUMBER(), and so on
EX:
SELECT employee_num, full_name Name, employee_id
FROM mtl_employees_current_view
WHERE (employee_num = NVL (:b1,employee_num)) AND (organization_id=:1)
ORDER BY employee_num; SELECT employee_num, full_name Name, employee_id
FROM mtl_employees_current_view
WHERE (employee_num = :b1) AND (organization_id=:1)
ORDER BY employee_num; If a column of type NUMBER is used in a WHERE clause to filter predicates with a literal value,
then use a TO_NUMBER function in the WHERE clause predicate to ensure you can use the index on the NUMBER column.
For example, if numcol is a column of type NUMBER, then a WHERE clause containing numcol=TO_NUMBER('') enables the database to use the index on numcol. If a query joins two tables, and if the join columns have different data types (for example, NUMBER and VARCHAR2),
then Oracle Database implicitly performs data type conversion. For example, if the join condition is varcol=numcol,
then the database implicitly converts the condition to TO_NUMBER(varcol)=numcol. If an index exists on the varcol column,
then explicitly set the type conversion to varcol=TO_CHAR(numcol), thus enabling the database to use the index.
16.5.3.3 Write Separate SQL Statements for Specific Tasks
It is always better to write separate SQL statements for different tasks, but if you must use one SQL statement,
then you can make a very complex statement slightly less complex by using the UNION ALL operator.
SELECT info
FROM tables
WHERE ...
AND somecolumn BETWEEN DECODE(:loval, 'ALL', somecolumn, :loval)
AND DECODE(:hival, 'ALL', somecolumn, :hival);
The database cannot use an index on the somecolumn column, because the expression involving that column uses the same column on both sides of the BETWEEN.
重写上边的语句, 可以走索引
SELECT /* change this half of UNION ALL if other half changes */ info
FROM tables
WHERE ...
AND somecolumn BETWEEN :loval AND :hival
AND (:hival != 'ALL' AND :loval != 'ALL')
UNION ALL
SELECT /* Change this half of UNION ALL if other half changes. */ info
FROM tables
WHERE ...
AND (:hival = 'ALL' OR :loval = 'ALL');
综上, 基本上是说, 你要对你查询中重要的列的类型做好控制, 尽量不要让隐式转换发生.
16.5.4 Controlling the Access Path and Join Order with Hints
你可以通过hint来指导oracle, 比如:
SELECT /*+ FULL(e) */ e.last_name
FROM employees e
WHERE e.job_id = 'CLERK';
Join order can have a significant effect on performance. The main objective of SQL tuning is to avoid performing unnecessary work to access rows that do not affect the result
Avoid a full-table scan if it is more efficient to get the required rows through an index.
Avoid using an index that fetches 10,000 rows from the driving table if you could instead use another index that fetches 100 rows.
Choose the join order so as to join fewer rows to tables later in the join order.
EX:
SELECT info
FROM taba a, tabb b, tabc c
WHERE a.acol BETWEEN 100 AND 200
AND b.bcol BETWEEN 10000 AND 20000
AND c.ccol BETWEEN 10000 AND 20000
AND a.key1 = b.key1
AND a.key2 = c.key2;
(1) Choose the driving table and the driving index (if any).
(2) Choose the best join order, driving to the best unused filters earliest.
(3) You can use the ORDERED or STAR hint to force the join order.
16.5.4.1 Use Caution When Managing Views
连接比较复杂的view时, 要特别小心
EX :
CREATE OR REPLACE VIEW emp_dept
AS
SELECT d.department_id, d.department_name, d.location_id,
e.employee_id, e.last_name, e.first_name, e.salary, e.job_id
FROM departments d
,employees e
WHERE e.department_id (+) = d.department_id; SELECT v.last_name, v.first_name, l.state_province
FROM locations l, emp_dept v
WHERE l.state_province = 'California'
AND v.location_id = l.location_id (+);
--------------------------------------------------------------------------------
| Operation | Name | Rows | Bytes| Cost | Pstart| Pstop |
--------------------------------------------------------------------------------
| SELECT STATEMENT | | | | | | |
| FILTER | | | | | | |
| NESTED LOOPS OUTER | | | | | | |
| VIEW |EMP_DEPT | | | | | |
| NESTED LOOPS OUTER | | | | | | |
| TABLE ACCESS FULL |DEPARTMEN | | | | | |
| TABLE ACCESS BY INDEX|EMPLOYEES | | | | | |
| INDEX RANGE SCAN |EMP_DEPAR | | | | | |
| TABLE ACCESS BY INDEX R|LOCATIONS | | | | | |
| INDEX UNIQUE SCAN |LOC_ID_PK | | | | | |
--------------------------------------------------------------------------------
16.5.4.2 Store Intermediate Results
materialized views 也是其中的一种
16.5.9.1 Combine Multiples Scans Using CASE Expressions
EX:
SELECT COUNT (*)
FROM employees
WHERE salary < 2000; SELECT COUNT (*)
FROM employees
WHERE salary BETWEEN 2000 AND 4000; SELECT COUNT (*)
FROM employees
WHERE salary>4000;
以上3个, 替换成一个更有效率的SQL, 利用 case
SELECT COUNT (CASE WHEN salary < 2000
THEN 1 ELSE null END) count1,
COUNT (CASE WHEN salary BETWEEN 2001 AND 4000
THEN 1 ELSE null END) count2,
COUNT (CASE WHEN salary > 4000
THEN 1 ELSE null END) count3
FROM employees;
16.5.9.3 Modify All the Data Needed in One Statement
一个事务, 结合在一起
EX:
BEGIN
FOR pos_rec IN (SELECT *
FROM order_positions
WHERE order_id = :id) LOOP
DELETE FROM order_positions -- 事务1
WHERE order_id = pos_rec.order_id AND
order_position = pos_rec.order_position;
END LOOP;
DELETE FROM orders -- 事务2
WHERE order_id = :id;
END;
以上, 事务1 和 事务2 其实是一个操作, 类似银行转账, 所以, 最好放在一个begin end 里.

16 SQL Tuning Overview的更多相关文章

  1. 【转】使用SQL Tuning Advisor STA优化SQL

    SQL优化器(SQL Tuning Advisor STA)是Oracle10g中推出的帮助DBA优化工具,它的特点是简单.智能,DBA值需要调用函数就可以给出一个性能很差的语句的优化结果.下面介绍一 ...

  2. 如何用 SQL Tuning Advisor (STA) 优化SQL语句

    在Oracle10g之前,优化SQL是个比较费力的技术活,不停的分析执行计划,加hint,分析统计信息等等.在10g中,Oracle推出了自己的SQL优化辅助工具: SQL优化器(SQL Tuning ...

  3. 使用ORACLE SQL Tuning advisor快速优化低效的SQL语句

    ORACLE10G以后版本的SQL Tuning advisor可以从以下四个方面给出优化方案 (1)为统计信息丢失或失效的对象收集统计信息   (2)考虑优化器的任何数据偏差.复杂谓词或失效的统计信 ...

  4. 老李分享: Oracle Performance Tuning Overview 翻译下

    1.2性能调优特性和工具 Effective data collection and analysis isessential for identifying and correcting perfo ...

  5. 老李分享: Oracle Performance Tuning Overview 翻译

    老李分享: Oracle Performance Tuning Overview 翻译   poptest是国内唯一一家培养测试开发工程师的培训机构,以学员能胜任自动化测试,性能测试,测试工具开发等工 ...

  6. Oracle调整顾问(SQL Tuning Advisor 与 SQL Access Advisor

    在Oracle数据库出现性能问题时,使用Oracle本身的工具包,给出合理的调优建议是比较省力的做法. tuning advisor 是对输入的sql set的执行计划进行优化accsee advis ...

  7. rac数据库默认sql tuning advisor,导致大量library cache lock

    rac数据库默认sql tuning advisor,导致大量library cache lock 问题现象:客户反映周六周日固定十点钟,一个程序会特别慢(大概10分钟),平时1到2秒.查看当时的日志 ...

  8. Oracle SQL Tuning Advisor 测试

    如果面对一个需要优化的SQL语句,没有很好的想法,可以先试试Oracle的SQL Tuning Advisor. SQL> select * from v$version; BANNER --- ...

  9. 怎样使用oracle 的DBMS_SQLTUNE package 来执行 Sql Tuning Advisor 进行sql 自己主动调优

     怎样使用oracle 的DBMS_SQLTUNE package 来执行 Sql Tuning Advisor 进行sql 自己主动调优 1>.这里简单举个样例来说明DBMS_SQLTUN ...

随机推荐

  1. Mac更换Sublime Text程序图标

    更换方法: 下载.icns格式一个图标.http://www.easyicon.net/language.en/iconsearch/sublime/ 终端执行:open /Applications/ ...

  2. 采用CSS3设计的登录界面,动态效果(动画)

    与上一篇的“采用CSS3设计的登陆界面”的相同,只是样式style添加了CSS3的动画元素. style内容如下: <style> html,body,div{ margin:0; pad ...

  3. 显示HTML文本

    + (NSAttributedString*)getAttributedStringFromHtmlString:(NSString*)htmlString{ return [[NSAttribute ...

  4. windows nslookup、tracert 常用命令

    nslookup www.baidu.com 可以指定查询的类型,可以查到DNS记录的生存时间还可以指定使用哪个DNS服务器进行解释. tracert www.baidu.com 路由

  5. hduoj 3459 Rubik 2×2×2

    http://acm.hdu.edu.cn/showproblem.php?pid=3459 Rubik 2×2×2 Time Limit: 10000/5000 MS (Java/Others)   ...

  6. 反射调用方法时的两种情况,走get set和不走get set

    @Test public void test1() throws Exception{  //获取User类  Class class1=Class.forName("cn.jbit.bea ...

  7. session 存储方式

    Session 的存储方式 在 php.ini 文件中,进行配置. 涉及配置参数: - session.save_handler - session.save_path 注意:这两个参数可以在 PHP ...

  8. 我们应该如何去了解JavaScript引擎的工作原理

    “读了你的几篇关于JS(变量对象.作用域.上下文.执行代码)的文章,我个人觉得有点抽象,难以深刻理解.我想请教下通过什么途径能够深入点的了解javascript解析引擎在执行代码前后是怎么工作的,ec ...

  9. VS 解决方案管理器和 编辑窗口同步 联动

    对于题目的解释就是   当我点击一下解决方案管理器中的 某一个文档时, 编辑窗口会联动的   同步到对应的窗口。之前好像被我无意中关掉了,今天重新建立一个项目无意中发现怎么设置了 如果想点击右边的文档 ...

  10. 如何写出优雅的Python之设置class缺省值

    今天有个需求时需要为某个类设置缺省值 最开始的代码如下: Class myClass def __init__(self,datalen=None,times=None): if datalen == ...