参考

https://cloud.tencent.com/developer/article/1162572

Index

  1. 主键索引「根据主键查询」

  2. 组合索引「多字段组合查询」

  3. 索引字段,索引失效情况

    1. where 子句中对字段进行函数、表达式操作

      1
      2
      3
      4
      5
      6
      7
      where upper(city)='TokYo' 或 City || 'X' like 'TOKYO%',

      select id from t where num/2=100 应改为: select id from t where num=100*2

      select * from emp where to_char(hire_date,'yyyymmdd')='20080411' (不使用)

      select * from emp where hire_date = to_char('20080411','yyyymmdd') (使用)

      建议:不要对索引字段进行函数、表达式操作

    2. 查询字段 is null 或 is not null

      建议:is not null 时永远不会使用索引。索引字段最好都是 NOT NULL,可通过设置默认值达到效果

    3. 使用了不等于操作符(<>、!=)

      解决:通过把不等于操作符改成 or,可以使用索引,避免全表扫描。例如,把 column<>’aaa’,改成 column<’aaa’ or column>’aaa’,就可以使用索引了

      建议:不等于改成 or

    4. 全模糊或左模糊查询

      1
      2
      3
      4
      5
      6
      where City like '%YOK%'

      where City like: City_bind_Variable xl_rao

      select * from emp where name like '%A' (不使用索引)
      select * from emp where name like 'A%' (使用索引)

      建议:尽量避免模糊查询。如果需要,则可以使用右模糊,不要使用全模糊或左模糊

    5. 使用 not in 不会走索引

      建议:用 not exists 或者(外联结 + 判断为空)来代替

    6. where 子句中比较的两个条件,一个有索引,一个没索引,使用 or 则会引起全表扫描

      例如:where A=:1 or B=:2, A 上有索引,B 上没索引,则比较 B=:2 时会重新开始全表扫描

    7. 组合索引,排序时应按照组合索引中各列的顺序进行排序,即使索引中只有一个列是要排序的

      例如:create index skip1 on emp5 (job,empno,date); select job,empno from emp5 where job=’manager’and empno=’10’order by job,empno,date desc; 实际上只是查询出符合 job=’manager’and empno=’10’条件的记录并按 date 降序排列,但是写成 order by date desc 性能较差

Select

  1. select count (*) from table;这样不带任何条件的 count 会引起全表扫描,并且没有任何业务意义,是一定要杜绝的

  2. 不要使用 in 操作符,这样数据库会进行全表扫描

  3. A>2 时 ORACLE 会先找出为 2 的记录索引再进行比较,而 A>=3 时 ORACLE 则直接找到 = 3 的记录索引

  4. UNION ALL:合并后直接返回。 UNION:合并去重后返回

    建议:如果结果集不重叠,建议使用UNION ALL

  5. WHERE 子句后面的条件顺序对大数据量表的查询会产生直接的影响

    1
    2
    Select * from zl_yhjbqk where dy_dj = '1K以下' and xh_bz=1
    Select * from zl_yhjbqk where xh_bz=1 and dy_dj = '1K以下'

Update

  1. update 语句,如果只更改 1、2 个字段,不要 update 全部字段,否则频繁调用会引起明显的性能消耗,同时带来大量日志