1.访问 Table 的方式
- Oracle 采用两种访问表中记录的方式
- A 全表扫描
- 就是按顺序的访问表中每一条记录 。oralce 采用一次读取多个数据库的方式优化全表扫描
- B: 通过ROWID访问表
- 你可以采用基于ROWID的访问方式,提高访问标的效率,因为ROWID是包含表中记录的物理位置信息,Oralce采用索引Index实现了数据和存储数据的物理位置。
2.清空共享池
alter system flush buffer_cache
3.选择最有效率的表名顺序(只在基于规则的优化器中有效)
alter system set optimizer_model=RULE
- ORALCE解析是从右边到左边的顺序处理 ,写在 oralce子句中最后的表是最先被处理。因此我们选记录条数最少的表作为基础表。
4.WHERE 子句中的连接顺序
- Oralce采用自上而下的顺序解析WHERE子句,因此我们要讲能够过滤掉最大记录的条件要放在WHERE子句的末尾
5. Select中子句的避免使用 “*”
- ORACLE 在解析过程中会将* 依次转换成所有的列名,这个工作是通过数据库字典完成的。
- 所以我们要将 “*” 转换成主键列(因为它一般都有索引)
6.记录条数的
- 也尽量不要使用 “*” 应该使用主键列 (因为它一般都有索引)
7.用WHERE子句替换Having
- 避免使用 having 子句,having只会在检索出所有记录结果后才对结果进行过滤,这个处理需要排序,统计等操作。如果能通过where子句限制记录数目,就使用where
8.使用表的别名 Alias
- 当SQL语句中连接多个表时,请使用个表的别名,兵把表的别名用户每个Column上,这样可以避免多个表中同名列发送的歧义和语法错误。
9.使用extists/not exists 代替 in/not in
- 1.设置基于成本的优化器
- alter system set optimizer_mode=ALL_ROWS 效率差不多
- 2.基于规则的优化器
- alter system set optimizer_mode=RULE
- 效率高
- select * from ids_emp e where exists/not exists (select * from ids_dept d where e.deptno=d.deptno and loc='a')
- select * from ids_emp where deptno in/not in (select deptno from ids_depts where loc='a')
9.使用表连接替换exists和not exists
- select * from ids_emp e,ids_detp d where e.deptno=d.deptno and d.loc='a'
- 替换
- select * from ids_emp e where exists,not (select * from ids_depts where e.deptno=d.deptno and d.loc='a')
10,使用 exists 代替 DISTINCT
- select distinct d.deptno,d.dname from ids_emp e,ids_deptno d where e.deptno=d.deptno
- select d.deptno,d.dname from ids_deptno d where exists (select * from ids_emp e where e.deptno=d.deptno);
11.常量的计算在语句被优化时候一次性完成。
- select * from emp where sal > 2400/12
- select * from emp where sal > 1200
- sleect * from emp where sal *1 2 > 2400 (sal不会使用索引没有办法优化)
12,in or 子句常会使用个工作表,是索引失效
- 如果不产生大量重复值,可以考虑把子句拆开,拆开的子句应该包含索引。
13.消除大型表数据的顺序存取
- 多层嵌套查询
- 笛卡尔集: select * from ids_emp e where e.deptno In (select deptno from deptno where dname='销售部')应该在 deptno 上建立索引
- 1.select * from ids_emp where (deptno=10 and dept=20) or empno=300;
- 这个还是使用的是 顺序检索
- 应该使用下面sql
- select * from ids_emp where deptno=10 an deptno=20 union select * from ids_emp where empno=300
14 避免相关子查询: 一个列的标签同时在主查询和WHERE子句中的查询中出现,那么很可能当主查询中的列值改变之后,子查询必须重新查询一次。查询嵌套层次越多,效率越低,因此应当尽量避免子查询。如果子查询不可避免,那么要在子查询中过滤掉尽可能多的行。