SQL statements follow a predictable clause order. Once you know the order, reading unfamiliar queries gets much easier.
The Standard Clause Order
SELECT columns
FROM table
WHERE row-level condition
GROUP BY grouping columns
HAVING group-level condition
ORDER BY sort order
LIMIT row count;
You don't need every clause every time — but the ones you do use must appear in this order, or the query fails.
Full Example
SELECT department, COUNT(*) AS total_employees
FROM employees
WHERE status = 'active'
GROUP BY department
HAVING COUNT(*) > 5
ORDER BY total_employees DESC
LIMIT 3;
This reads as: from active employees, group by department, keep only departments with more than 5 people, sort by headcount, and show the top 3.
Keywords Are Case-Insensitive — Your Data Isn't Always
SELECT, select, and Select all work identically — keywords are case-insensitive. But whether 'Aman' = 'aman' matches depends on the column's collation (MySQL is usually case-insensitive by default; PostgreSQL string comparison is case-sensitive by default). Writing keywords in UPPERCASE is a convention, not a rule — it just makes queries easier to scan.
Statement Termination
Each statement ends with a semicolon ;. Most tools tolerate a missing semicolon on a single statement, but it's required when running multiple statements together.
Common Mistakes
- Writing
WHEREafterGROUP BY— alwaysWHEREbeforeGROUP BY, beforeHAVING - Trying to filter an aggregate with
WHEREinstead ofHAVING(see WHERE vs HAVING) - Forgetting that
LIMITalways goes last
Interview Relevance
A frequent whiteboard question: "In what order does SQL actually execute these clauses?" The written order and the logical execution order differ — SQL evaluates FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT, even though you type SELECT first. This is why you can't reference a column alias (defined in SELECT) inside a WHERE clause in most databases — WHERE runs before SELECT does.
Practice Question
Rewrite this incorrect query so it's syntactically valid: SELECT dept, COUNT(*) FROM employees GROUP BY dept WHERE salary > 40000 ORDER BY dept;