How to Write Optimal SQL Queries

后端 未结 9 1572
余生分开走
余生分开走 2021-02-01 06:47

I\'ve searched around stackoverflow but everybody asks to optimize queries they\'ve already done.

I want to know, the basic stuff on what to do, what to avoid when creat

9条回答
  •  终归单人心
    2021-02-01 07:32

    adding some tips to the list :

    Using EXISTS/NOT EXISTS in place of IN/NOT IN for indexed columns

     --instead of 
     SELECT * FROM table1
      WHERE id1 NOT IN (SELECT id2 FROM table2)
    
     --you better write
     SELECT * FROM table1 WHERE NOT EXISTS (SELECT 1 FROM table2 WHERE id1=id2)  
    

    Avoid using UNION when its possible to use UNION ALL
    when you dont need to exclude duplicated rows or you are sure it wont return duplicated rows

    Avoid using HAVING when its possible to use WHERE

     --instead of 
     SELECT col1, sum(col2) 
       FROM table1
      GROUP BY col1
     HAVING col1 > 0
    
     --you better write :
     SELECT col1, sum(col2)
       FROM table1
      WHERE col1 > 0
     GROUP BY col1
    

    Use EXISTS instead of DISTINCT when you have one-to-many table joins

    --instead of
    SELECT distinct a.col1, a.col2
      FROM table1 a, table2 b
     WHERE a.id = b.id
    
    --you better write
    SELECT a.col1, a.col2
      FROM table1 a
     WHERE EXISTS (SELECT 1 FROM table2 b where a.id = b.id)  
    

    I hope this few tips helps, looking forward more tips ;)

提交回复
热议问题