SQL Statement Structure
SQL Statement Structure
Definition
Every SQL statement follows a clause-based structure: a small set of keywords, each introducing a clause, assembled in a fixed order. Learning to read SQL is largely learning to recognize these clauses and the order they must appear in.
How It Works
The canonical query skeleton, in the order clauses must be written (not the order they're logically evaluated in):
sqlSELECT column_list -- 6. which columns to return FROM table_name -- 1. which table(s) to read JOIN other_table ON ... -- 2. combine with other tables WHERE row_condition -- 3. filter individual rows GROUP BY column_list -- 4. collapse rows into groups HAVING group_condition -- 5. filter groups ORDER BY column_list -- 7. sort the final result LIMIT n; -- 8. cap the row count
The gap between written order and logical evaluation order trips up many learners: WHERE runs before GROUP BY, and HAVING runs after GROUP BY — which is exactly why WHERE cannot reference an aggregate like COUNT(*), but HAVING can.
A statement ends with a semicolon ;, which separates it from the next statement in a script — required by most engines when multiple statements appear together, optional for a single interactive statement in some tools.
Edge Cases and Pitfalls
- Writing
WHERE COUNT(*) > 5is a common beginner mistake —WHEREfilters rows before grouping happens, so aggregates aren't available yet;HAVING COUNT(*) > 5is correct. - Clause order in the written statement is fixed and cannot be rearranged (e.g.,
WHEREmust come afterFROM/JOIN, beforeGROUP BY) — the engine's parser will reject an out-of-order statement. - Omitting a semicolon between statements in a batch script can silently concatenate two statements into one, changing behavior without necessarily raising an error.
Key Takeaways
- SQL statements are built from an ordered set of clauses; the required written order is FROM/JOIN → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT.
- Written order and logical evaluation order are different — this explains WHERE vs HAVING.
- A statement is terminated by a semicolon, which matters most once more than one statement appears together.