Chapter 8 · Lesson 5 of 8

Where Window Functions Fit

See where window functions run in the logical query order, and rank grouped regional totals with RANK() over a GROUP BY result.

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.

Sample data

This lesson loads the sales table (8 rows) into DuckDB in your browser with one click, so you can run every example without uploading anything.

Setup SQL for sales
CREATE OR REPLACE TABLE sales (
    id INTEGER,
    salesperson VARCHAR,
    region VARCHAR,
    amount DECIMAL(10,2),
    quantity INTEGER,
    sale_date DATE
  );

INSERT INTO sales VALUES
    (1, 'Alice', 'West', 1200, 3, '2024-01-05'),
    (2, 'Bob', 'East', 850, 2, '2024-01-08'),
    (3, 'Alice', 'West', 640, 1, '2024-01-11'),
    (4, 'Diana', 'South', 430, 5, '2024-01-12'),
    (5, 'Eve', 'West', 1500, 4, '2024-02-01'),
    (6, 'Frank', 'East', 920, 2, '2024-02-03'),
    (7, 'Grace', 'North', 760, 2, '2024-02-07'),
    (8, 'Bob', 'East', 1100, 3, '2024-02-10');

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.

Hint: Use SUM(amount) AS total_amount plus ROW_NUMBER() OVER (ORDER BY SUM(amount) DESC).

Run your query in the editor and the lesson checks the result automatically.

Open this lesson in the SQL editor

Lessons in Execution Order

Understand the logical order in which SQL evaluates FROM, WHERE, GROUP BY, HAVING, window functions, SELECT, ORDER BY, and LIMIT.

  1. 01 · Written Order vs Logical Order
  2. 02 · FROM and JOIN Build the Rows First
  3. 03 · WHERE Filters Before GROUP BY
  4. 04 · HAVING Filters After GROUP BY
  5. 05 · Where Window Functions Fit
  6. 06 · Why Window Functions Cannot Go Directly in WHERE
  7. 07 · Why SELECT Aliases Work in ORDER BY
  8. 08 · LIMIT Happens at the End

Related guides