🔷 SQL: How Queries Actually Execute
You write SELECT ... FROM ... WHERE ... but SQL runs them in a totally different order:
FROM → JOIN → WHERE → GROUP BY → HAVING → SELECT → DISTINCT → ORDER BY → LIMIT
Why this matters: You can't reference a column alias from SELECT in your WHERE clause — WHERE runs first. You can't filter a window function in WHERE — it's computed during SELECT. This execution order explains 90% of "why doesn't this query work?" moments.
Practice Questions
Q: What happens if you write
WHERE total_sales > 100 and total_sales is an alias from SELECT SUM(sales) AS total_sales?