Skip to content
We areTOP 1%
DBMS & SQL · Pro · Topic 4 of 5

SQL: Window Functions

6 questions.
Your progress0%
1st Visit
0/6
2nd Visit
0/6
Revise
0/6

Overview

A window function computes a value for each row from a set of related rows, without collapsing the rows the way GROUP BY does. The OVER clause defines the window: PARTITION BY splits the rows into groups, ORDER BY orders the rows inside each group, and an optional frame such as ROWS BETWEEN 2 PRECEDING AND CURRENT ROW limits which rows are included. Ranking functions (ROW_NUMBER, RANK, DENSE_RANK), offset functions (LAG, LEAD) and running aggregates (SUM(...) OVER) solve most interview problems. Look for "top n per group", "previous day", "running total" or "moving average". MySQL supports window functions from version 8.0.

SELECT day, amount,
       SUM(amount) OVER (ORDER BY day) AS running_total,
       LAG(amount)  OVER (ORDER BY day) AS prev_amount
FROM daily_sales;

Questions

Sign in to track your progress

Your checkboxes, streak and activity heatmap are saved to your account and sync across devices. It is free.
Sign in with email

New here? Create an account