Learn SQL
SQL Execution Order Explained: Why WHERE, GROUP BY, HAVING, SELECT, and LIMIT Behave Differently
SQL is written in one order but understood in another; learning the logical order explains many beginner surprises.
On This Page
SQL is written one way and reasoned about another way
SQL queries are written for humans, but the logical steps happen in a different order. Once you learn that order, confusing behavior starts to make sense.
SQL for Files gives you guided exercises that make this visible with small tables before you apply the same reasoning to your own data files.
A useful logical order model
FROM
JOIN
WHERE
GROUP BY
HAVING
WINDOW FUNCTIONS
SELECT
DISTINCT
ORDER BY
LIMITReal engines optimize internally, but this teaching model explains most SQL rules and error messages.
WHERE, GROUP BY, and HAVING happen at different times
WHERE filters individual rows before grouping. GROUP BY forms summary groups. HAVING filters those groups after aggregate values have been calculated.
SELECT region, SUM(amount) AS total_amount
FROM sales
GROUP BY region
HAVING SUM(amount) > 2000;Window functions, aliases, and LIMIT make more sense late in the order
Window functions run after filtering and grouping, which is why you often need a subquery to filter on a window result. SELECT aliases are visible to ORDER BY because ORDER BY happens later. LIMIT cuts down the final result at the end.
SELECT name, salary * 0.10 AS annual_bonus
FROM employees
ORDER BY annual_bonus DESC
LIMIT 5;Practice the Execution Order chapter
- Read queries in logical order, not only written order.
- Practice how JOINs build rows before WHERE filters them.
- Compare WHERE and HAVING with grouped results.
- Use subqueries for filtering window function results.
- Finish by seeing why ORDER BY can use SELECT aliases and LIMIT happens last.
Continue in the editor
Open SQL for Files to add your own CSV, JSON, or Parquet files and try these examples locally in your browser.
Open editorRelated guides
SQL DISTINCT, GROUP BY, and HAVING: From Unique Values to Grouped Reports
DISTINCT cleans up repeated values, GROUP BY creates summaries per category, and HAVING filters those summaries after aggregation.
SQL Window Functions Explained: OVER, PARTITION BY, Running Totals, and LAG
Window functions add context beside each row: totals, group totals, ranks, running totals, and previous values without losing detail.
SQL WHERE Clause Explained: Filtering Rows with AND, OR, and LIKE
Filtering is where SQL starts to feel useful: keep only the rows that answer your question, then combine conditions as your questions get sharper.