Careeroza
Order of Execution
Written Order vs Logical Order
You write a query in one order, but the database evaluates it in another. Knowing the logical order explains many errors.
| Step | Clause | What happens |
|---|---|---|
| 1 | FROM / JOIN | pick the tables and combine them |
| 2 | WHERE | filter rows |
| 3 | GROUP BY | form groups |
| 4 | HAVING | filter groups |
| 5 | SELECT | compute output columns and aliases |
| 6 | DISTINCT | remove duplicate rows |
| 7 | ORDER BY | sort |
| 8 | LIMIT / OFFSET | cut the result |
Why It Matters
- A column alias defined in
SELECTcannot be used inWHERE(WHERE runs first), but it can be used inORDER BY. - Aggregates cannot appear in
WHERE, because groups do not exist yet. UseHAVING. LIMITruns last, so it limits the final, sorted result.
Example
The alias Total works in ORDER BY:
SELECT CustomerID, SUM(Amount) AS Total
FROM Orders
GROUP BY CustomerID
ORDER BY Total DESC;Result: 6 rows
| CustomerID | Total |
|---|---|
| 2 | 412 |
| 3 | 320.75 |
| 1 | 301.75 |
| 7 | 198.4 |
| 5 | 150 |
| 4 | 116.9 |
Exercise
Exercise: For each department, show the average salary rounded to 0 decimals, only for departments whose average is above 60000, highest first.
Show answer
SELECT Department, ROUND(AVG(Salary), 0) AS AvgSalary
FROM Employees
GROUP BY Department
HAVING AVG(Salary) > 60000
ORDER BY AvgSalary DESC;