Order of Perations

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:

  1. FROM and JOIN clauses
  2. WHERE clause
  3. GROUP BY clause
  4. Aggregates and window functions
  5. HAVING clause
  6. SELECT clause
  7. DISTINCT keyword
  8. ORDER BY clause
  9. LIMIT and OFFSET clauses
  10. TOP
LexicalLogical
SELECTFROM
DISTINCTJOIN
TOPWHERE
[AGGREGATION]GROUP BY
FROM[AGGREGATION]
JOINHAVING
WHERESELECT
GROUP BYDISTINCT
HAVINGORDER BY
ORDER BYTOP / LIMIT

Example 1 #

SELECT City,
  Profit
FROM dbo.Orders
ORDER BY Profit DESC;
LexicalLogical
SELECTFROM
FROMSELECT
ORDER BYORDER 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;
LexicalLogical
SELECTFROM
FROMJOIN -> INNER
JOINGROUP BY
GROUP BY[Aggregate]
ORDER BYSELECT
ORDER BY