4 Hours

7. Advanced Analytics: Window Functions

Analytics

The OVER Magic

Window functions are the secret weapon of senior SQL developers. Unlike GROUP BY, they do not collapse rows. They let you perform a calculation across a window of rows while keeping the individual data visible. This is essential for ranking, running totals, and moving averages.

The Window Signature

A window function is identified by the OVER() clause. It tells Postgres: 'Run this calculation across these rows, but don't group them.

SQL
-- Calculate a running total of sales
SELECT 
  date, 
  amount,
  SUM(amount) OVER (ORDER BY date) as running_total
FROM sales;

PARTITION BY: Grouping without Collapsing

PARTITION BY is like GROUP BY for window functions. It resets the calculation for every unique value in that column. Perfect for finding the top 3 selling products in every single category.

SQL
-- Rank products by price within each category
SELECT 
  category, 
  name, 
  price,
  RANK() OVER (PARTITION BY category ORDER BY price DESC) as price_rank
FROM products;

The Window Toolkit

  • ROW_NUMBER(): Assigns a unique sequential number (1, 2, 3...) to each row.
  • RANK() vs DENSE_RANK(): Handles ties. RANK leaves gaps (1, 2, 2, 4); DENSE_RANK does not (1, 2, 2, 3).
  • LEAD() & LAG(): Access data from the NEXT or PREVIOUS row. Great for calculating growth rates.
  • NTILE(n): Divides rows into n buckets (e.g., Quartiles or Percentiles).

Step-by-Step: Building a Leaderboard

  1. Identify Order: What are you ranking by? (e.g., score DESC).
  2. Choose Scope: Do you want a global rank or per-region? (Global = OVER(), Per-region = PARTITION BY region).
  3. Select Function: Use RANK() for official positions.
  4. Filter Results: Wrap in a CTE or Subquery if you only want the Top 10.

Knowledge Check

Ready to test your understanding of 7. Advanced Analytics: Window Functions?

Back