ORACLE SQL optimization

(1)       Select the most efficient table name order (only valid in the rule-based optimizer):
ORACLE's parser processes the table names in the FROM clause from right to left, and the FROM clause is written at the end The table (the base table driving table) will be processed first. In the case of multiple tables included in the FROM clause, you must select the table with the least number of records as the base table. If there are more than 3 tables to join the query, then you need to select the intersection table as the base table, and the intersection table refers to the table that is referenced by other tables.
(2)       The join order in the WHERE clause. :
ORACLE parses the WHERE clause in a bottom-up order. According to this principle, the connection between tables must be written before other WHERE conditions, and those conditions that can filter out the maximum number of records must be written at the end of the WHERE clause.
( 3)       Avoid using '*' in the SELECT clause:
During the parsing process, ORACLE will convert '*' into all column names in turn. This work is done by querying the data dictionary, which means that it will cost more Time
(4)       Reduce the number of database accesses:
ORACLE performs a lot of work internally: parsing SQL statements, estimating index utilization, binding variables, reading data blocks, etc.;
(5)       in SQL*Plus, SQL*Forms and Pro Resetting the ARRAYSIZE parameter in *C can increase the amount of retrieved data for each database access, the recommended value is 200
(6)       Use the DECODE function to reduce processing time:
Use the DECODE function to avoid repeated scanning of the same records or repeated connections to the same table.
(7)       Integrate simple, unrelated database access:
If you have several simple database query statements, you can combine them into one query (even if there is no relationship between them)
(8)       Delete duplicate records:
the most efficient Example of delete duplicate records method (because ROWID is used):
DELETE FROM EMP E WHERE E.ROWID > (SELECT MIN(X.ROWID) 
FROM EMP X WHERE X.EMP_NO = E.EMP_NO);
(9)       Use TRUNCATE instead of DELETE:
When deleting records in a table, under normal circumstances, rollback segments are used to store information that can be recovered. If you do not have a COMMIT transaction, ORACLE will restore the data to the state before the deletion (to be precise, restore to the state before the delete command was executed) and when TRUNCATE is used, the rollback segment no longer stores any recoverable information. When the command is run, the data cannot be recovered. Therefore, few resources are called, and the execution time will also be Very short. (Translator's note: TRUNCATE is only applicable to delete the whole table, TRUNCATE is DDL not DML)
(10)  Use COMMIT as much as possible:
Whenever possible, use COMMIT as much as possible in the program, so that the performance of the program is improved, and the demand It will also be reduced by the resources 
released by COMMIT: Resources released by COMMIT: 
a. Information on the rollback segment used to restore data. 
b. Locks acquired by program statements 
c. Space in the redo log buffer 
d. ORACLE replaces the HAVING clause with the Where clause to manage the internal costs of the above three resources
(11) 
: Avoid using the HAVING clause, HAVING will only filter the result set after all records have been retrieved. This processing requires Sorting, totaling and other operations. If you can limit the number of records through the WHERE clause, it can reduce the overhead in this regard. (In non-oracle) on, where, having these three clauses can be added conditions, on is Execute first, where comes second, and having last, because on filters the records that do not meet the conditions before performing statistics, it can reduce the data to be processed by intermediate operations. It is reasonable to say that the speed should be the fastest, and where should also be It is faster than having, because it performs sum after filtering the data, and only uses on when two tables are joined, so when there is one table, there is only a comparison between where and having. In the case of query statistics of this single table, if the conditions to be filtered do not involve the fields to be calculated, then their results are the same, but the rushmore technique can be used where, but having cannot, the latter is slower in terms of speed. If the calculated field is involved, it means that the value of this field is uncertain before it is calculated. According to the workflow written in the previous article, the action time of where is completed before the calculation, and the having is only after the calculation. works, so in this case the results of the two will be different. In multi-table join query, on works earlier than where. The system first combines multiple tables into a temporary table according to the join conditions between each table, then filters by where, and then calculates, and then filters by having. It can be seen that, in order for the filter condition to play a correct role, we must first understand when the condition should work, and then decide where to place it
(12)  Reduce the query on the table:
In the SQL statement containing the subquery, Pay special attention to reducing queries to the table. Example:
     SELECT TAB_NAME FROM TABLES WHERE (TAB_NAME,DB_VER) = ( SELECT
TAB_NAME,DB_VER FROM TAB_COLUMNS WHERE VERSION = 604)
(13)  Improve SQL efficiency through internal functions.:
Complex SQL often sacrifices execution efficiency. Can master the above application functions to solve The method of the problem is very meaningful in actual work
(14)  Use the alias of the table (Alias):
When connecting multiple tables in the SQL statement, please use the alias of the table and prefix the alias to each Column. This way As a result, the parsing time can be reduced and the syntax errors caused by Column ambiguity can be reduced.
(15)  Use EXISTS instead of IN and NOT EXISTS instead of NOT IN:
In many queries based on the underlying table, in order to satisfy a condition, often A join on another table is required. In this case, using EXISTS (or NOT EXISTS ) will generally improve the efficiency of the query. In a subquery, the NOT IN clause will perform an inner sort and merge. Either way In all cases, NOT IN is the least efficient (because it performs a full table traversal of the table in the subquery). To avoid using NOT IN, we can rewrite it as Outer Joins or NOT EXISTS.
Example :
(efficient) SELECT * FROM EMP (base table) WHERE EMPNO > 0 AND   EXISTS  (SELECT 'X' FROM DEPT WHERE DEPT.DEPTNO = EMP.DEPTNO AND LOC = 'MELB')
(Inefficient) SELECT * FROM EMP (basic table) WHERE EMPNO > 0 AND DEPTNO  IN (SELECT DEPTNO FROM DEPT WHERE LOC = 'MELB')
(16)  Identify ' inefficient execution' SQL statements:
Although there are currently various There are endless graphical tools for optimization, but writing your own SQL tool to solve the problem is always the best way:
SELECT EXECUTIONS , DISK_READS, BUFFER_GETS, 
ROUND((BUFFER_GETS-DISK_READS)/BUFFER_GETS,2) Hit_radio, 
ROUND(DISK_READS/ EXECUTIONS,2) Reads_per_run, 
SQL_TEXT 
FROM V$SQLAREA 
WHERE EXECUTIONS>0 
AND BUFFER_GETS > 0 
AND (BUFFER_GETS-DISK_READS)/BUFFER_GETS < 0.8 
ORDER BY 4 DESC;

 

(17) 用索引提高效率:
索引是表的一个概念部分,用来提高检索数据的效率,ORACLE使用了一个复杂的自平衡B-tree结构. 通常,通过索引查询数据比全表扫描要快. 当ORACLE找出执行查询和Update语句的最佳路径时, ORACLE优化器将使用索引. 同样在联结多个表时使用索引也可以提高效率. 另一个使用索引的好处是,它提供了主键(primary key)的唯一性验证.。那些LONG或LONG RAW数据类型, 你可以索引几乎所有的列. 通常, 在大型表中使用索引特别有效. 当然,你也会发现, 在扫描小表时,使用索引同样能提高效率. 虽然使用索引能得到查询效率的提高,但是我们也必须注意到它的代价. 索引需要空间来存储,也需要定期维护, 每当有记录在表中增减或索引列被修改时, 索引本身也会被修改. 这意味着每条记录的INSERT , DELETE , UPDATE将为此多付出4 , 5 次的磁盘I/O . 因为索引需要额外的存储空间和处理,那些不必要的索引反而会使查询反应时间变慢.。定期的重构索引是有必要的.:
ALTER  INDEX <INDEXNAME> REBUILD <TABLESPACENAME>
(18) 用EXISTS替换DISTINCT:
当提交一个包含一对多表信息(比如部门表和雇员表)的查询时,避免在SELECT子句中使用DISTINCT. 一般可以考虑用EXIST替换, EXISTS 使查询更为迅速,因为RDBMS核心模块将在子查询的条件一旦满足后,立刻返回结果. 例子:
       (低效): 
SELECT  DISTINCT  DEPT_NO,DEPT_NAME  FROM  DEPT D , EMP E 
WHERE  D.DEPT_NO = E.DEPT_NO 
(高效): 
SELECT  DEPT_NO,DEPT_NAME  FROM  DEPT D  WHERE  EXISTS ( SELECT ‘X' 
FROM  EMP E  WHERE E.DEPT_NO = D.DEPT_NO);
(19) sql语句用大写的;因为oracle总是先解析sql语句,把小写的字母转换成大写的再执行
(20) 在java代码中尽量少用连接符“+”连接字符串!
(21) 避免在索引列上使用NOT 通常, 
我们要避免在索引列上使用NOT, NOT会产生在和在索引列上使用函数相同的影响. 当ORACLE”遇到”NOT,他就会停止使用索引转而执行全表扫描.
(22) 避免在索引列上使用计算.
WHERE子句中,如果索引列是函数的一部分.优化器将不使用索引而使用全表扫描. 
举例: 
低效: 
SELECT … FROM  DEPT  WHERE SAL * 12 > 25000; 
高效: 
SELECT … FROM DEPT WHERE SAL > 25000/12;
(23) 用>=替代>
高效: 
SELECT * FROM  EMP  WHERE  DEPTNO >=4 
低效: 
SELECT * FROM EMP WHERE DEPTNO >3 
两者的区别在于, 前者DBMS将直接跳到第一个DEPT等于4的记录而后者将首先定位到DEPTNO=3的记录并且向前扫描到第一个DEPT大于3的记录.
(24) 用UNION替换OR (适用于索引列)
通常情况下, 用UNION替换WHERE子句中的OR将会起到较好的效果. 对索引列使用OR将造成全表扫描. 注意, 以上规则只针对多个索引列有效. 如果有column没有被索引, 查询效率可能会因为你没有选择OR而降低. 在下面的例子中, LOC_ID 和REGION上都建有索引. 
高效: 
SELECT LOC_ID , LOC_DESC , REGION 
FROM LOCATION 
WHERE LOC_ID = 10 
UNION 
SELECT LOC_ID , LOC_DESC , REGION 
FROM LOCATION 
WHERE REGION = “MELBOURNE” 
低效: 
SELECT LOC_ID , LOC_DESC , REGION 
FROM LOCATION 
WHERE LOC_ID = 10 OR REGION = “MELBOURNE” 
如果你坚持要用OR, 那就需要返回记录最少的索引列写在最前面.
(25) 用IN来替换OR  
这是一条简单易记的规则,但是实际的执行效果还须检验,在ORACLE8i下,两者的执行路径似乎是相同的. 
低效: 
SELECT…. FROM LOCATION WHERE LOC_ID = 10 OR LOC_ID = 20 OR LOC_ID = 30 
高效 
SELECT… FROM LOCATION WHERE LOC_IN  IN (10,20,30);
(26) 避免在索引列上使用IS NULL和IS NOT NULL
避免在索引中使用任何可以为空的列,ORACLE将无法使用该索引.对于单列索引,如果列包含空值,索引中将不存在此记录. 对于复合索引,如果每个列都为空,索引中同样不存在此记录. 如果至少有一个列不为空,则记录存在于索引中.举例: 如果唯一性索引建立在表的A列和B列上, 并且表中存在一条记录的A,B值为(123,null) , ORACLE将不接受下一条具有相同A,B值(123,null)的记录(插入). 然而如果所有的索引列都为空,ORACLE将认为整个键值为空而空不等于空. 因此你可以插入1000 条具有相同键值的记录,当然它们都是空! 因为空值不存在于索引列中,所以WHERE子句中对索引列进行空值比较将使ORACLE停用该索引.
低效: (索引失效) 
SELECT … FROM  DEPARTMENT  WHERE  DEPT_CODE IS NOT NULL; 
高效: (索引有效) 
SELECT … FROM  DEPARTMENT  WHERE  DEPT_CODE >=0;
(27) 总是使用索引的第一个列
如果索引是建立在多个列上, 只有在它的第一个列(leading column)被where子句引用时,优化器才会选择使用该索引. 这也是一条简单而重要的规则,当仅引用索引的第二个列时,优化器使用了全表扫描而忽略了索引
(28) 用UNION-ALL 替换UNION ( 如果有可能的话)
当SQL语句需要UNION两个查询结果集合时,这两个结果集合会以UNION-ALL的方式被合并, 然后在输出最终结果前进行排序. 如果用UNION ALL替代UNION, 这样排序就不是必要了. 效率就会因此得到提高. 需要注意的是,UNION ALL 将重复输出两个结果集合中相同记录. 因此各位还是要从业务需求分析使用UNION ALL的可行性. UNION 将对结果集合排序,这个操作会使用到SORT_AREA_SIZE这块内存. 对于这块内存的优化也是相当重要的. 下面的SQL可以用来查询排序的消耗量
低效: 
SELECT  ACCT_NUM, BALANCE_AMT 
FROM  DEBIT_TRANSACTIONS 
WHERE TRAN_DATE = '31-DEC-95' 
UNION 
SELECT ACCT_NUM, BALANCE_AMT 
FROM DEBIT_TRANSACTIONS 
WHERE TRAN_DATE = '31-DEC-95' 
高效: 
SELECT ACCT_NUM, BALANCE_AMT 
FROM DEBIT_TRANSACTIONS 
WHERE TRAN_DATE = '31-DEC-95' 
UNION ALL 
SELECT ACCT_NUM, BALANCE_AMT 
FROM DEBIT_TRANSACTIONS 
WHERE TRAN_DATE = '31-DEC-95'
(29) 用WHERE替代ORDER BY
ORDER BY 子句只在两种严格的条件下使用索引. 
ORDER BY中所有的列必须包含在相同的索引中并保持在索引中的排列顺序. 
ORDER BY中所有的列必须定义为非空. 
WHERE子句使用的索引和ORDER BY子句中所使用的索引不能并列.
例如: 
表DEPT包含以下列: 
DEPT_CODE PK NOT NULL 
DEPT_DESC NOT NULL 
DEPT_TYPE NULL
低效: (索引不被使用) 
SELECT DEPT_CODE FROM  DEPT  ORDER BY  DEPT_TYPE 
高效: (使用索引) 
SELECT DEPT_CODE  FROM  DEPT  WHERE  DEPT_TYPE > 0
(30) 避免改变索引列的类型.:
当比较不同数据类型的数据时, ORACLE自动对列进行简单的类型转换. 
假设 EMPNO是一个数值类型的索引列. 
SELECT …  FROM EMP  WHERE  EMPNO = ‘123' 
实际上,经过ORACLE类型转换, 语句转化为: 
SELECT …  FROM EMP  WHERE  EMPNO = TO_NUMBER(‘123') 
幸运的是,类型转换没有发生在索引列上,索引的用途没有被改变. 
现在,假设EMP_TYPE是一个字符类型的索引列. 
SELECT …  FROM EMP  WHERE EMP_TYPE = 123 
这个语句被ORACLE转换为: 
SELECT …  FROM EMP  WHERETO_NUMBER(EMP_TYPE)=123 
因为内部发生的类型转换, 这个索引将不会被用到! 为了避免ORACLE对你的SQL进行隐式的类型转换, 最好把类型转换用显式表现出来. 注意当字符和数值比较时, ORACLE会优先转换数值类型到字符类型
(31) 需要当心的WHERE子句:
某些SELECT 语句中的WHERE子句不使用索引. 这里有一些例子. 
在下面的例子里, (1)‘!=' 将不使用索引. 记住, 索引只能告诉你什么存在于表中, 而不能告诉你什么不存在于表中. (2) ‘||'是字符连接函数. 就象其他函数那样, 停用了索引. (3) ‘+'是数学函数. 就象其他数学函数那样, 停用了索引. (4)相同的索引列不能互相比较,这将会启用全表扫描.
(32) a. 如果检索数据量超过30%的表中记录数.使用索引将没有显著的效率提高. 
b. 在特定情况下, 使用索引也许会比全表扫描慢, 但这是同一个数量级上的区别. 而通常情况下,使用索引比全表扫描要块几倍乃至几千倍!
(33) 避免使用耗费资源的操作:
带有DISTINCT,UNION,MINUS,INTERSECT,ORDER BY的SQL语句会启动SQL引擎 
执行耗费资源的排序(SORT)功能. DISTINCT需要一次排序操作, 而其他的至少需要执行两次排序. 通常, 带有UNION, MINUS , INTERSECT的SQL语句都可以用其他方式重写. 如果你的数据库的SORT_AREA_SIZE调配得好, 使用UNION , MINUS, INTERSECT也是可以考虑的, 毕竟它们的可读性很强
(34) 优化GROUP BY:
提高GROUP BY 语句的效率, 可以通过将不需要的记录在GROUP BY 之前过滤掉.下面两个查询返回相同结果但第二个明显就快了许多.
低效: 
SELECT JOB , AVG(SAL) 
FROM EMP 
GROUP JOB 
HAVING JOB = ‘PRESIDENT' 
OR JOB = ‘MANAGER' 
高效: 
SELECT JOB , AVG(SAL) 
FROM EMP 
WHERE JOB = ‘PRESIDENT' 
OR JOB = ‘MANAGER' 
GROUP JOB

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324618258&siteId=291194637