转ORACLE SQL 优化

1.访问 Table 的方式 

Java代码   收藏代码
  1. Oracle 采用两种访问表中记录的方式  
  2. A 全表扫描  
  3.    就是按顺序的访问表中每一条记录 。oralce 采用一次读取多个数据库的方式优化全表扫描  
  4.   
  5. B: 通过ROWID访问表  
  6.    你可以采用基于ROWID的访问方式,提高访问标的效率,因为ROWID是包含表中记录的物理位置信息,Oralce采用索引Index实现了数据和存储数据的物理位置。  



2.清空共享池 
  alter system flush buffer_cache 


3.选择最有效率的表名顺序(只在基于规则的优化器中有效) 
   alter system set optimizer_model=RULE 

Java代码   收藏代码
  1. ORALCE解析是从右边到左边的顺序处理 ,写在 oralce子句中最后的表是最先被处理。因此我们选记录条数最少的表作为基础表。  



4.WHERE 子句中的连接顺序 

Java代码   收藏代码
  1. Oralce采用自上而下的顺序解析WHERE子句,因此我们要讲能够过滤掉最大记录的条件要放在WHERE子句的末尾  



5. Select中子句的避免使用 “*” 

Java代码   收藏代码
  1. ORACLE 在解析过程中会将* 依次转换成所有的列名,这个工作是通过数据库字典完成的。   
  2. 所以我们要将 “*” 转换成主键列(因为它一般都有索引)  



6.记录条数的 

Java代码   收藏代码
  1. 也尽量不要使用 “*”  应该使用主键列 (因为它一般都有索引)  



7.用WHERE子句替换Having 

Java代码   收藏代码
  1. 避免使用 having 子句,having只会在检索出所有记录结果后才对结果进行过滤,这个处理需要排序,统计等操作。如果能通过where子句限制记录数目,就使用where  



8.使用表的别名 Alias 

Java代码   收藏代码
  1. 当SQL语句中连接多个表时,请使用个表的别名,兵把表的别名用户每个Column上,这样可以避免多个表中同名列发送的歧义和语法错误。  



9.使用extists/not exists  代替 in/not in 

Java代码   收藏代码
  1. 1.设置基于成本的优化器  
  2.  alter system set optimizer_mode=ALL_ROWS   效率差不多  
  3.   
  4. 2.基于规则的优化器  
  5.  alter system set optimizer_mode=RULE     
  6.   
  7. 效率高  
  8. select * from  ids_emp e where exists/not exists  (select * from ids_dept d where e.deptno=d.deptno and loc='a')   
  9.   
  10. select * from ids_emp where deptno in/not in (select deptno from ids_depts where loc='a')  



9.使用表连接替换exists和not exists 

Java代码   收藏代码
  1. select * from ids_emp e,ids_detp d where e.deptno=d.deptno and d.loc='a'  
  2. 替换  
  3. select * from ids_emp e where exists,not (select * from ids_depts where e.deptno=d.deptno and d.loc='a')  



10,使用 exists 代替 DISTINCT 

Java代码   收藏代码
  1. select distinct d.deptno,d.dname from ids_emp e,ids_deptno d where e.deptno=d.deptno  
  2.   
  3. select d.deptno,d.dname from ids_deptno d where exists (select * from ids_emp e where e.deptno=d.deptno);  



11.常量的计算在语句被优化时候一次性完成。 

扫描二维码关注公众号,回复: 1296965 查看本文章
Java代码   收藏代码
  1. select * from emp where sal > 2400/12  
  2. select * from emp where sal > 1200  
  3. sleect * from emp where sal *1 2 > 2400 (sal不会使用索引没有办法优化)  



12,in or 子句常会使用个工作表,是索引失效 

Java代码   收藏代码
  1. 如果不产生大量重复值,可以考虑把子句拆开,拆开的子句应该包含索引。  



13.消除大型表数据的顺序存取 

Java代码   收藏代码
  1. 多层嵌套查询  
  2. 笛卡尔集: select * from ids_emp e where e.deptno In (select deptno from deptno where dname='销售部')应该在 deptno 上建立索引  
  3.   
  4. 1.select * from ids_emp where (deptno=10 and dept=20) or empno=300;  
  5. 这个还是使用的是 顺序检索  
  6. 应该使用下面sql  
  7. select * from ids_emp where deptno=10 an deptno=20 union select * from ids_emp where empno=300  



14 避免相关子查询: 一个列的标签同时在主查询和WHERE子句中的查询中出现,那么很可能当主查询中的列值改变之后,子查询必须重新查询一次。查询嵌套层次越多,效率越低,因此应当尽量避免子查询。如果子查询不可避免,那么要在子查询中过滤掉尽可能多的行。

猜你喜欢

转载自lumingming1987.iteye.com/blog/1864653