Learn SQL Lesson
Where Window Functions Fit
Window functions belong later in SQL's logical order. A good mental model is:
FROM → WHERE → GROUP BY → HAVING → WINDOW FUNCTIONS → SELECT → ORDER BY → LIMIT
That means window functions run after filtering and grouping, but before the final ordering and limiting.
You still write window functions in the `SELECT` list or sometimes in `ORDER BY`. The logical order is about when their input rows exist, not where the expression is typed.
This is why window functions can do things like rank grouped results, but usually cannot be used directly in `WHERE` or `GROUP BY`.
For example, this query first groups sales by region, then ranks those regional totals:
SELECT region,
SUM(amount) AS total_amount,
ROW_NUMBER() OVER (ORDER BY SUM(amount) DESC) AS region_rank
FROM sales
GROUP BY region
The grouped rows exist first, and then the window function ranks them.
Practice challenge
Group sales by region, then rank those grouped totals from highest to lowest. Return region, total_amount, and region_rank, ordered by region_rank.