In our AWS re/Start Databases module today, we covered the optional clauses of a SELECT statement: WHERE, GROUP BY, HAVING, and ORDER BY.
If you're like me, you probably write queries in this logical order:
SELECT name, COUNT(*)
FROM city
WHERE population > 1000
GROUP BY name
HAVING COUNT(*) > 5
ORDER BY name;
But here is the catch: the database does not read your query from top to bottom. It follows a specific internal execution order. If you don't know this order, you will constantly run into weird errors like "column alias not found" or "invalid use of group function."
Here is the actual order SQL processes the query:
1. FROM
The database first figures out which table to pull data from.
2. WHERE
It filters the rows before grouping. This is why you cannot use aggregate functions (like COUNT() or SUM()) in a WHERE clause, and why you cannot use an alias you defined in the SELECT step (because the SELECT hasn't happened yet!).
3. GROUP BY
It groups the remaining rows together based on your criteria.
4. HAVING
It filters the groups created in the previous step. This is where you are allowed to use aggregate functions to filter your results (e.g., HAVING COUNT(*) > 5).
5. SELECT
The database now calculates the final columns, applies your math/aggregations, and assigns your column aliases.
6. ORDER BY
Finally, it sorts the output. Because this runs after SELECT, it is the only clause where you can use your column aliases to sort.
The Bottom Line
Understanding this execution order is a game-changer. It explains why WHERE and HAVING exist separately, and why your aliases work in ORDER BY but fail in WHERE.
Have you ever run into a weird SQL error because of execution order? Let me know below!
#sql
#databases
#aws-restart
#cloud
#data
Loading article