Window function

What it is

A window function calculates a value for a row using other rows that
belong to a defined window. It can assign a rank, compare a value
with a previous row, or compute an aggregate that stays attached to
each row. A report can show every day's reading together with a
cumulative total, keeping the detail available for people who want
to understand why the total changed.

In SQL, the expression uses an OVER clause to describe its window.
Partitioning breaks the input into independent groups such as one
series per device. Ordering defines the sequence within each group.
Some functions, including an aggregate used as a window function,
also use a frame. The frame is the part of the ordered partition
that contributes to the result for the current row. A frame can
expand from the start of a sequence, move across a fixed number of
rows, or include rows based on peers or a value range.

The grouping stages of the query determine the rows available to the
window calculation. If the query first creates one row per device
and date, a seven-row frame can work over daily observations. If it
receives raw events directly, seven rows could cover many hours or
only a few seconds. The query's final ordering is another separate
choice. The sequence used to compute a running value does not by
itself tell the result consumer how rows will be delivered.

Why it matters

A common requirement in a report is to see both the number and the
reason it moved. A list of sales can display each amount alongside a
weekly running total. A quality review can show where a reading
falls within the results from its own device. Keeping the original
row alongside the calculation lets the reader trace a change back to
the sale, observation or event that contributed to it.

Window functions make definitions sensitive to the match between the
question and the input grain. A three-row moving average is useful
if each row is a day and the dates are complete. If a sensor stops
reporting for two days, the same expression can span five calendar
days when it reaches across the gap. Choose explicitly whether the
report should exclude the absent days, include them as unknowns, or
represent them with a business-approved replacement such as zero.
Each policy leads to a different interpretation of the result.

Ranking also needs a definition of equality. In a ranking by
delivery time, identical times could share a rank even if the
resulting sequence has gaps. Another report may need a predictable
unique position for every record. Adding a stable secondary key can
support that case. Take care to keep intended ties where they
matter. The test suite can use rows with matching amounts and
missing dates to make both decisions visible.

What it looks like in practice

Imagine a daily usage report for several sites. First decide what a
daily reading means when records arrive from different timezones.
Group the events into one row per local date and site and retain a
count of contributing events. For a rolling figure that covers
calendar days, build a date series explicitly and merge the
aggregates with it. Then run the window by site, using date for its
calculation order and an explicit frame. Return the site, date,
daily total and the window value side by side.

A second column can compare each day with its predecessor. A useful
test includes the first day of a series, a date with no readings and
two devices whose reporting schedules differ. Check which previous
record the expression receives in each case. The first day might
have no comparison. For a gap, the report's desired definition tells
you whether to compare with the last actual reading or with the
previous calendar day, even when its value is unknown.

Engineer's reporting-system case study describes collecting and
analysing data in an automated workflow that produces regular PDF
reports. A window calculation is one way an illustrative SQL-backed
report can support the same need for recurring comparisons. The
calculation should have a readable label and a documented grain. If
a reader sees a line labelled seven-day average, the implementation
and its checks should make it easy to establish exactly which seven
days contribute.

Where it goes wrong

An implicit frame can surprise a query author who expects every
displayed row to add one step to a cumulative result. When ordering
values have peers, a range-based frame can include those peers
together. A running total can appear to jump on several rows at
once. Specify the desired frame and test tied timestamps. Decide
whether a second order key identifies an actual sequence or merely
supplies a stable display order.

Filtering can also move the starting point of a calculation. If a
report asks for the last seven displayed dates and the first
displayed row needs the preceding six days, the window needs access
to those earlier rows. Compute the necessary history before applying
the display filter. A test with known daily totals can show when the
beginning of a chart accidentally starts with too little data.

Finally, measure how the query executes on representative
partitions. Sorting a large workload can consume memory and time,
particularly if several window definitions require different orders.
Combine compatible calculations where it improves clarity, and
inspect the execution plan with the data size expected in
production. Keep the deterministic input and the expected rows with
the query tests. These checks make a later change to the grouping
stage, timezone policy or frame explainable to the people who rely
on the report.

Further reading

  * PostgreSQL window functions. Describes functions, peer rows and
the treatment of frames.

  * PostgreSQL window-function tutorial. Shows the relationship
between the OVER clause and rows produced by a query.

  * SQLite window functions. Documents frame types, boundaries and
examples in SQLite.

hThis page on the web	URL:https://engineer.company/glossary/window-function/	engineer.company	70
