SQLPathLab
Practical SQL Guide · MySQL 8.0

SQL clause order and logical execution

Understand the logical order of FROM, WHERE, GROUP BY, HAVING, SELECT, and ORDER BY.

Problem and reasoning

The first written clause is not necessarily evaluated first. Logical order explains why a SELECT alias usually cannot be referenced from WHERE and helps decide whether a filter belongs before or after grouping. A useful model is FROM/JOIN, WHERE, GROUP BY, HAVING, SELECT, DISTINCT, ORDER BY, and LIMIT.

When debugging a complex query, verify the base rows produced by FROM and JOIN, then add WHERE, GROUP BY, and HAVING one step at a time. This reveals exactly where row count or meaning changes.

Logical order is a reasoning model, not a promise about physical execution. The optimizer may rewrite the plan while preserving SQL semantics.

Examples

Sample table

Table:orders
orders
departmentamount
Sales 1200
IT 900
Sales 1500
HR 700

Before / Not recommended

SELECT department, SUM(amount) AS total FROM orders WHERE amount >= 1300 GROUP BY department ORDER BY total DESC;

Before result

result
departmenttotal
Sales 1500

After / Recommended

SELECT department, SUM(amount) AS total FROM orders GROUP BY department HAVING SUM(amount) >= 1300 ORDER BY total DESC;

After result

result
departmenttotal
Sales 2700

Why it is better:WHERE removes detail rows below 1300 before department totals are calculated; HAVING filters after full department totals exist. They are not interchangeable.

Was this explanation clear?