302 — Window Functions

Advanced

Master SQL window functions to perform calculations across sets of rows without collapsing them. Learn ROW_NUMBER, RANK, LAG, LEAD, running totals, moving averages, and frame clauses to build powerful analytics queries.

Learning Objectives

1
Understand the difference between GROUP BY and window functions
2
Use OVER(), PARTITION BY, and ORDER BY to define windows
3
Apply ROW_NUMBER(), RANK(), and DENSE_RANK() for ranking
4
Use LAG() and LEAD() to compare rows with their neighbors
5
Calculate running totals and moving averages
6
Understand frame clauses (ROWS BETWEEN) for precise window control
Step 1

What are window functions?

Window functions let you perform calculations across a set of rows related to the current row — without collapsing those rows into one. Start by seeing the problem they solve.

Commands to Run

sqlite3 ecommerce.db "SELECT customer_id, order_date, total_amount FROM orders WHERE customer_id IN (1, 2) ORDER BY customer_id, order_date;"
sqlite3 ecommerce.db "SELECT customer_id, SUM(total_amount) AS total_spent FROM orders WHERE customer_id IN (1, 2) GROUP BY customer_id;"
sqlite3 ecommerce.db "SELECT customer_id, order_date, total_amount, SUM(total_amount) OVER (PARTITION BY customer_id) AS customer_total FROM orders WHERE customer_id IN (1, 2) ORDER BY customer_id, order_date;"

What This Does

The first query shows individual orders — you see every row. The second query uses GROUP BY to get totals — but it collapses rows, losing the individual order details. The third query uses a window function: SUM(total_amount) OVER (PARTITION BY customer_id). It adds the customer's total to every row WITHOUT collapsing them. You keep the detail AND get the aggregate. That's the superpower of window functions.

Expected Outcome

First query: individual orders for customers 1 and 2 with dates and amounts. Second query: just two rows with total per customer. Third query: every individual order row, but with an additional column showing that customer's total on every row.

Pro Tips

  • 1
    Mental model: GROUP BY gives one row per group; window functions give a value per row FROM the group
  • 2
    The OVER() clause is what makes a function a window function
  • 3
    Window functions never reduce the number of rows in your result
Was this step helpful?

All Steps (0 / 14 completed)