Optimizing SQL Performance: A Guide to Query Execution Order

Spread the love

SQL Order Of Execution

In SQL, the order of execution tells us about the sequence in which parts of the query are executed.

  1. FROM: The query begins by identifying the table or tables from which it will retrieve data. It is self-explanatory that data is needed before you can do anything with it.
  2. JOIN: If the user is using SQL JOINS , complete set of data needs to be created.
  3. WHERE: The WHERE clause will help filter the undesired data out.
  4. GROUP BY: If the user is working with aggregates, the GROUP BY will group the data so that AGGREGATE Functions like SUM, AVG, etc. can work.
  5. HAVING: If the user wants to Filter the aggregate result created by GROUP BY clause, HAVING will help them in achieving that.
  6. SELECT: The `SELECT` clause is used to specify which columns you want to include in the result set.
  7. DISTINCT: If you use the `DISTINCT` keyword in your query, it eliminates duplicate rows from the result set after all the previous steps are executed.
  8. ORDER BY: You can specify the sorting order (ascending or descending) for each column.
  9. LIMIT / OFFSET or TOP : User can now specify the number of rows it wants using LIMIT or TOP (if using SQL Server).

Reader should keep in mind that this is the general order of execution in SQL, it is basically a framework for understanding SQL queries. It is important to note that not all queries will have all these clauses and order can vary depending on user requirement.

Read More: Learn SQL Fast

Source: Microsoft T-SQL Documentation