zoukankan      html  css  js  c++  java
  • sql常用优化

       最近因工作需要,查找资料整理了一下sql的常见优化,具体如下:

    1.尽量避免全表扫描,一般在where或order by 涉及的列上建立索引;

    2.尽量避免在where子句中对索引字段进行null值判断,否则会导致引擎弃用索引而进行全表扫描;
       select id from table where num is null;
       可以在num表字段设置默认值为0,且为非空字段,然后sql修改为:
       select id from table where num =0;

    3.尽量避免在where条件中对索引字段使用!=或<>,否则会导致全表扫描;

    4.尽量避免在where条件中对索引字段使用or,否则会导致全表扫描;
       如:select id from table num =10 or num = 20;
       可以修改为
       select id form table num =10
       union all
       select id form table num =20;

    5.in 和not in慎用,否则会导致全表扫描;
       如:select id from table where num in (1,2,3);
      可修改为:select id from table where num between 1 and 3;

    6.慎用like '%%',否则会导致全表扫描;
      如:select id from table where name like '%abc%';

    7.尽量避免在where后对索引字段字段进行表达式操作,否则会导致全表扫描;
       如:select id from table where num/2 = 20;
      可修改为: select * from table num = 20*2;

    8.尽量避免在where后对索引字段进行函数操作,否则会导致全表扫描;
       如:select id from table where substring(name,1,3) = 'abc';
       可修改为:select id from table where name like 'abc%';

    9.对索引字段不要在where子句中“=”左边进行函数,算术运算或其他表达式运算,否则会导致全表扫描;
       如:select id from table where num+1=5;
       可修改为:select id from table where num = 5-1;

    10.尽量避免没必要的查询,
    如:select col1,col2 into temp_table from table where 1=0;
    可修改为:create table temp_table(需要的table表列);

    11.尽量使用exists 代替 in;
       如:select num from tableA where num in (select num from tableB);
      可修改为:select num from tableA where num exists (select 1 from tableB where tableB.num =tableA.num);

    12.尽可能的使用 varchar 代替 char ,因为首先变长字段存储空间小,可以节省存储空间,
        其次对于查询来说,在一个相对较小的字段内搜索效率显然要高些;

    13.避免使用 select * from t,用具体的字段列表代替“*”,不要返回用不到的任何字段;

    14.如果使用到了临时表,在存储过程的最后务必将所有的临时表显式删除,先 truncate table 

     ,然后 drop table ,这样可以避免系统表的较长时间锁定;

    15.统计查询数据条数尽量避免用count(*);
        如:select count(*) from table;
        应修改为: select count(1) from table;

    16.在可以使用UNION ALL的语句里,尽量避免使用了UNION,因为UNION 会将各查询子集的记录做比较,
        故比起UNION ALL ,通常速度都会慢上许多;

    17.慎用distinct关键字,因为distinct会对数据进行比较,过滤掉重复数据,需要耗费对应的时间;

    18.insert into select批量插入,尽量避免一个个循环插入。

         难免会有疏漏,如果发现请即使指出,谢谢!

  • 相关阅读:
    Ftp、Ftps与Sftp之间的区别
    Previous Workflow Versions in Nintex Workflow
    Span<T>
    .NET Core 2.0及.NET Standard 2.0 Description
    Announcing Windows Template Studio in UWP
    安装.Net Standard 2.0, Impressive
    SQL 给视图赋权限
    Visual Studio for Mac中的ASP.NET Core
    How the Microsoft Bot Framework Changed Where My Friends and I Eat: Part 1
    用于Azure功能的Visual Studio 2017工具
  • 原文地址:https://www.cnblogs.com/lidelin/p/9923940.html
Copyright © 2011-2022 走看看