Order of Execution in The Select Statement

FROM —> WHERE—> GROUP BY—> HAVING—>SELECT—> ORDER BY

This is why you cannot use what you haveĀ  aliases in the GROUP BY but you can use them in the SELECT statement

sql server - Order Of Execution of the SQL query - Stack Overflow

1. FROM and JOINs

  • Initial stage determining the working set of data.
  • Executes the FROM clause and subsequent JOINs.
  • May involve the creation of temporary tables for joined data.

2. WHERE

  • First-pass application of WHERE constraints.
  • Discards rows that do not meet specified conditions.
  • Constraints can only access columns directly from tables in the FROM clause.

3. GROUP BY

  • Remaining rows after WHERE constraints are applied are grouped.
  • Grouping based on common values in the specified column.
  • Use when aggregate functions are present in the query.

4. HAVING

  • Applies constraints to grouped rows if GROUP BY is present.
  • Discards grouped rows that fail to satisfy the constraint.
  • Aliases not accessible in this step in most databases.

5. SELECT

  • Computation of expressions in the SELECT part of the query.
  • Finalizes the data to be presented in the result set.

6. DISTINCT

  • Discards rows with duplicate values in the specified DISTINCT column.
  • Further refines the result set based on uniqueness.

7. ORDER BY

  • Sorts rows based on specified data in ascending or descending order.
  • Aliases from SELECT expressions are accessible at this stage.

8. LIMIT / OFFSET

  • Final step in the process.
  • Discards rows falling outside the specified range.
  • Defines the ultimate set of rows returned from the query.

Conclusion:

While not every query incorporates all outlined parts, SQL’s flexibility empowers developers and data analysts. This structured sequence allows for efficient data manipulation without the need for extensive coding. Mastering the order of execution enhances your ability to craft precise and impactful SQL queries.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top