liveBook · Manning

Window function

As explained in DuckDB in Action

A window is a defined set of rows over which a SQL window function computes a value for each current row.

A window function computes a value for each current row while looking across a defined set of rows. Unlike GROUP BY aggregation, it preserves every row. Define the window with OVER(), optionally adding PARTITION BY, ORDER BY, and a frame. section 4.5

Use window functions to:

Top readings per system

Rank within each system, then keep the top two ranks: WITH ranked_readings AS ( SELECT *, dense_rank() OVER (PARTITION BY system_id ORDER BY power DESC) AS rnk FROM readings ) SELECT * FROM ranked_readings WHERE rnk <= 2 ORDER BY system_id, rnk; section 4.5.1

Compare successive prices

Order prices by date and access the previous value: SELECT valid_from, value, lag(value) OVER validity AS previous_value, value - lag(value, 1, value) OVER validity AS change FROM prices WINDOW validity AS (ORDER BY valid_from); Use a CTE before applying an aggregate to the window result, because window calls cannot be nested inside aggregate functions. section 4.5.4

How DuckDB in Action covers it

How deep it goes
Defines OVER, partitions, ordering, and frames, then demonstrates ranking and row comparisons; detailed frame variations remain limited.
Examples
Demonstrates power-reading top-n queries, per-system averages, and month-by-month renewable-energy price changes.
What it assumes
Assumes SQL querying, ingested data, and basic data types; teaches window mechanics through concrete DuckDB datasets.
What you can do after
Apply it via DuckDB SQL to rank partitions, calculate windowed aggregates, compare adjacent rows, and filter computed results.
How it connects
Connects window functions with SQL aggregation, partitions, common table expressions, named windows, lag, lead, and QUALIFY.

Also explained in

Compare how 3 books explain window function →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of DuckDB in Action. The section links point to the parts of the book it draws on.