Part 07 / Topic 7 of 8
The WINDOW clause
Several functions over the same window means repeating the OVER — unless you name it once:
SELECT customer_id, order_date,
ROW_NUMBER() OVER w AS nth_order,
LAG(order_date) OVER w AS previous,
FIRST_VALUE(order_date) OVER w AS first_ever
FROM orders
WINDOW w AS (PARTITION BY customer_id ORDER BY order_date)
ORDER BY customer_id, order_date
LIMIT 6;
customer_id | order_date | nth_order | previous | first_ever
-------------+------------+-----------+------------+------------
1 | 2025-01-10 | 1 | | 2025-01-10
1 | 2025-02-14 | 2 | 2025-01-10 | 2025-01-10
1 | 2025-03-30 | 3 | 2025-02-14 | 2025-01-10
2 | 2025-01-25 | 1 | | 2025-01-25
2 | 2025-03-18 | 2 | 2025-01-25 | 2025-01-25
3 | 2025-02-20 | 1 | | 2025-02-20
(6 rows)
WINDOW w AS (...) sits between HAVING and ORDER BY, defines the window once, and every OVER w reuses it — one place to edit when the partitioning changes, and visibly the same window for every function, which is half the readability win.
🧪 Quick quiz — answer from memory, then check.
- What does the WINDOW clause buy you?
- Where does it sit in the query?
Show the answers
- One named window definition reused by many functions — no duplication to drift apart.
- After HAVING, before ORDER BY.
Exercise 7: Top three, properly filtered
What to do: The three priciest products with their rank — remembering WHERE can't see the rank.
Sample output:
name | price | rnk
---------------+---------+-----
Laptop Pro 14 | 1200.00 | 1
Laptop Air 13 | 950.00 | 2
Phone X | 799.00 | 3
(3 rows)
💡 Hint: rank in a CTE, filter outside.
Show the solution to Exercise 7
-- Exercise 7: Top three, properly filtered
WITH ranked AS (
SELECT name, price,
RANK() OVER (ORDER BY price DESC) AS rnk
FROM products
)
SELECT name, price, rnk FROM ranked WHERE rnk <= 3;