sql优化, sql怎么写效率高

来源:互联网 发布:windows设置时间同步 编辑:程序博客网 时间:2024/04/29 06:36

/***************************
sql优化, sql怎么写效率高
***************************/
1、 表名顺序: 扫描器是从后面往前找
from s, c, sc
记录最少的表写最后面
有关联关系的写最后

2、 where子句的连接顺序: 扫描器是从后面往前找
可以过滤大量记录的条件语句放到where语句的最后面
关联条件连接语句放在最后面

3、 select后面尽量避免使用 *

4、 尽量使用decode函数,减少处理事件

--decodeselect sum(decode(sex, '男', 1, 0)), sum(decode(sex, '女', 1,0)) from SPORTER t

5、 删除重复记录,最有效的方法

delete from s s1 where s1.rowid > (    select min(s2.rowid) from s s2 where s1.sname=s2.sname)

6、 用truncate代替delete
用truncate删除的数据不再放到回滚段中,不可恢复

7、 尽量多使用commit,commit会尽量的释放资源
释放回滚段上的信息
释放程序语句获得的锁
释放redo log buffer中的资源

8、 where子句替换having子句,能放到where的过滤条件,绝对不放having里面(where是全局过滤,having是分组过滤)
条件语句执行顺序: 先on…后where…最后having

9、 使用表的别名alias
每个列之前加上别名,减少由列的歧义引起的语法错误

10、 尽量使用exists和not exists,少用in和not in

如:select * from emp where emp.deptno in (    select * from dept where loc='NEW YORK')优化为:select * from emp where exists (    select * from dept where emp.deptno=dept.deptno and loc='NEW YORK')

11、 尽量的使用索引(index)提高效率,索引列可以提高该列的检索效率

12、 用exists替换distinct

如:select distinct d.deptno, d.dname from dept d, emp e where d.deptno=e.deptno优化为:select d.deptno, d.dname from dept d where exists (select '1' from emp e where d.deptno=e.deptno)

13、 尽量使用大写: oracle执行sql语句,会把小写转大写再执行

14、 避免在索引列上使用not
避免在索引列上使用计算: select * from emp where 12* sal > 10000
避免在索引列上使用is null 和 is not null
避免在索引列上使用模糊like
避免修改索引列的类型

原创粉丝点击