How to Write Optimal SQL Queries

后端 未结 9 1600
余生分开走
余生分开走 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条回答
  •  Happy的楠姐
    2021-02-01 07:26

    My simple rules to write a query:

    1. Write FROM clause from the most smallest table. This helps to find data more efficiently as we make searching in smaller amount of data.

    2. At first you should write INNER JOIN, then LEFT OUTER JOIN. This helps to decrease quantity of rows where SQL Engine will search your data.

      For example:

      SELECT 
          pe.Name,
          de.Name,
          bu.Name
      FROM dbo.Persons pe
      INNER JOIN dbo.Departments de ON pe.ID = de.id_Person -- at first INNER JOIN
      LEFT JOIN dbo.Bureau bu ON bu.ID = de.id_Bureau -- then LEFT OUTER JOIN
      
    3. Use aliases and schema name to avoid schema scanning by SQL Server. As using schema name helps to cashe your query plan for ad-hoc queries that can be reusable by other users, not only for your queries.

    4. Avoid using SELECT * ...

提交回复
热议问题