SQL Order Of Execution
In SQL, the order of execution tells us about the sequence in which parts of the query are executed.
- 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.
- JOIN: If the user is using SQL JOINS , complete set of data needs to be created.
- WHERE: The WHERE clause will help filter the undesired data out.
- 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.
- HAVING: If the user wants to Filter the aggregate result created by GROUP BY clause, HAVING will help them in achieving that.
- SELECT: The `SELECT` clause is used to specify which columns you want to include in the result set.
- 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.
- ORDER BY: You can specify the sorting order (ascending or descending) for each column.
- 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