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.

Published 2026-05-09·Updated 2026-05-09

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
LIMIT

Real 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

  1. Read queries in logical order, not only written order.
  2. Practice how JOINs build rows before WHERE filters them.
  3. Compare WHERE and HAVING with grouped results.
  4. Use subqueries for filtering window function results.
  5. Finish by seeing why ORDER BY can use SELECT aliases and LIMIT happens last.