Learn SQL
SQL Window Functions Explained: OVER, PARTITION BY, Running Totals, and LAG
Window functions add context beside each row: totals, group totals, ranks, running totals, and previous values without losing detail.
On This Page
Window functions keep detail and add context
GROUP BY summarizes rows and collapses detail. Window functions are different: they keep every detail row visible and add calculations beside it.
In SQL for Files, you can practice these patterns on sample sales data and then reuse them on local files in your browser with DuckDB WASM.
OVER defines the window
OVER () means the whole result set is the calculation window. PARTITION BY splits that window into smaller groups, such as one window per region.
SELECT id, region, amount,
SUM(amount) OVER (PARTITION BY region) AS region_total
FROM sales_2;ORDER BY enables running totals and rankings
ORDER BY inside a window makes row sequence matter. That is how you build running totals, rankings, and time-based comparisons.
SELECT salesperson, sale_date, amount,
SUM(amount) OVER (
PARTITION BY salesperson
ORDER BY sale_date
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS running_amount
FROM sales_2;ROW_NUMBER and LAG answer practical questions
ROW_NUMBER ranks rows inside each group. LAG looks backward to a previous row. Together, they support top-N queries, deduplication, and change-over-time analysis.
SELECT salesperson, sale_date, amount,
LAG(amount) OVER (PARTITION BY salesperson ORDER BY sale_date) AS previous_amount
FROM sales_2;Practice the Window Functions chapter
- Use OVER () to add a company-wide total beside each row.
- Use PARTITION BY for region-specific totals.
- Add ORDER BY and a frame for running totals.
- Practice ROW_NUMBER, LAG, and other common window functions.
Continue in the editor
Open SQL for Files to add your own CSV, JSON, or Parquet files and try these examples locally in your browser.
Open editorRelated guides
SQL Aggregate Functions: COUNT, SUM, MIN, MAX, and AVG Explained
Aggregate functions turn many rows into useful summary values, which is the foundation of reporting, dashboards, and quick data checks.
SQL Execution Order Explained: Why WHERE, GROUP BY, HAVING, SELECT, and LIMIT Behave Differently
SQL is written in one order but understood in another; learning the logical order explains many beginner surprises.
Practical SQL Examples for CSV, JSON, and Parquet Files
A compact collection of SQL patterns you can adapt for local file analysis in SQL for Files.