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
My simple rules to write a query:
Write FROM
clause from the most smallest table. This helps to find data more efficiently as we make searching in smaller amount of data.
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
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.
Avoid using SELECT * ...