Window Functions

Filtering Window Function Results

Senior Data Analyst
March 9, 2026
5 min read

The Problem

I wanted "Only the top-ranked order per customer." But `WHERE ROW_NUMBER() = 1` doesn't work.

The Solution: Wrap in a CTE

WITH ranked AS (

SELECT

*,

ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY amount DESC) AS rn

FROM orders

)

SELECT * FROM ranked WHERE rn = 1;

Why This Works

Window functions are evaluated AFTER the WHERE clause in SQL's order of operations. By wrapping the query in a CTE, the window function runs first, then you can filter on its result.

*Day 69: Named Windows (WINDOW Clause).*

Ready to put your knowledge into practice?

Join SQL Mastery and learn through interactive exercises.