The order of operations within SQL can be confusing as the written order of query clauses are different from the order of execution.
Below is a diagram showing the written order compared to the order of execution followed by an explanation of these.
![The Essential Guide to SQL’s Execution Order](https://www.kdnuggets.com/wp-content/uploads/ferrer_essential_guide_sql_execution_order_3.png)
(https://www.kdnuggets.com/the-essential-guide-to-sql-execution-order)
Select
- Selects the columns required from the table
- A * (asterix) can be used to reference all the columns, otherwise column names need to be written out
From
- Which table the data is coming from
Where
- Filters rows based on certain conditions stated
- e.g. where fruit='Apple' or profit>50
Group By
- Group by certain columns to then aggregate
Having
- Filter groups based on aggregate calculations
- Similar to where but used for aggregations
Order by
- Sort the results based on certain conditions
- Specify asc (ascending) or desc (descending)
- e.g. order by profit DESC
Limit
- Restrict certain number of rows
- Limit 5 (will return 5 rows)
Example of full code in written order
SELECT department_id, AVG(salary) AS avg_salary
FROM employees
WHERE job_title = 'Developer'
GROUP BY department_id
HAVING AVG(salary) > 60000
ORDER BY avg_salary DESC
LIMIT 5;