SQL Order of Operation
#
Understanding the order of operations and the logical processing order in SQL is crucial when constructing complex queries. It helps you predict how the query will be executed, avoid mistakes, and optimize performance.
Order of Operations (Logical Processing Order)
#
The logical processing order follows:
- FROM and JOIN clauses
- WHERE clause
- GROUP BY clause
- Aggregates and window functions
- HAVING clause
- SELECT clause
- DISTINCT keyword
- ORDER BY clause
- LIMIT and OFFSET clauses
TOP
Lexical | Logical |
---|
SELECT | FROM |
DISTINCT | JOIN |
TOP | WHERE |
[AGGREGATION] | GROUP BY |
FROM | [AGGREGATION] |
JOIN | HAVING |
WHERE | SELECT |
GROUP BY | DISTINCT |
HAVING | ORDER BY |
ORDER BY | TOP / LIMIT |
Example 1
#
SELECT City,
Profit
FROM dbo.Orders
ORDER BY Profit DESC;
Lexical | Logical |
---|
SELECT | FROM |
FROM | SELECT |
ORDER BY | ORDER BY |
Example 2
#
SELECT o.City,
AVG(o.Profit) AS Average_Profit
FROM Orders AS o
JOIN(
SELECT TOP(3) City,
SUM(Profit) AS Total_Profit
FROM dbo.Orders
GROUP BY City
ORDER BY Total_Profit DESC
) AS sub
ON o.City = sub.City
GROUP BY o.City
ORDER BY o.City,
Average_Profit;
Lexical | Logical |
---|
SELECT | FROM |
FROM | JOIN -> INNER |
JOIN | GROUP BY |
GROUP BY | [Aggregate] |
ORDER BY | SELECT |
| ORDER BY |