Window Functions — Complete Guide
Window Functions — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of PostgreSQL Tutorial on Toolliyo Academy.
On this page
PostgreSQL Tutorial · Lesson 18 of 100
Window Functions
SQL → Advanced
SQL · 1 — Queries · ~6 min · PostgreSQL — SQL & Queries
What is this?
Window functions compute across related rows without collapsing them like GROUP BY. OVER defines the partition and order — ROW_NUMBER, RANK, LAG, SUM OVER rows for running totals.
Why should you care?
Flipkart wants each product’s price rank within its category on the same row as the product — window functions, not self-joins.
See it live — copy this example
Run in pgAdmin or psql.
SELECT
product_id,
category,
price,
RANK() OVER (PARTITION BY category ORDER BY price DESC) AS price_rank
FROM products;
What happened?
- PARTITION BY category resets ranking per category.
- ORDER BY price DESC makes expensive items rank 1.
- Every product row stays; rank appears beside it.
Practice next
- Run the window query on products.
- Compare with GROUP BY — note row count difference.
- Add LAG(price) OVER (PARTITION BY category ORDER BY price) for previous price.
- SUM(total_amount) OVER (PARTITION BY customer_id ORDER BY created_at) for running spend.
- ROW_NUMBER to dedupe: keep latest row per customer_id in a CTE.
Remember
OVER keeps detail rows while adding analytics columns. PARTITION BY is like GROUP BY without collapsing. LAG/LEAD compare to neighbor rows.
PostgresVerse category leaderboard
Merchandising UI shows price_rank per category without a second API call.
Outcome: PM spots overpriced SKUs sitting at rank 1 in budget categories.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!