{"canonical_url":"https://engineer.company/glossary/window-function/","content_markdown":"# Window function\n\n## What it is\n\nA window function calculates a value for a row using other rows that belong to a\ndefined window. It can assign a rank, compare a value with a previous row, or\ncompute an aggregate that stays attached to each row. A report can show every\nday's reading together with a cumulative total, keeping the detail available for\npeople who want to understand why the total changed.\n\nIn SQL, the expression uses an OVER clause to describe its window. Partitioning\nbreaks the input into independent groups such as one series per device. Ordering\ndefines the sequence within each group. Some functions, including an aggregate\nused as a window function, also use a frame. The frame is the part of the\nordered partition that contributes to the result for the current row. A frame\ncan expand from the start of a sequence, move across a fixed number of rows, or\ninclude rows based on peers or a value range.\n\nThe grouping stages of the query determine the rows available to the window\ncalculation. If the query first creates one row per device and date, a seven-row\nframe can work over daily observations. If it receives raw events directly,\nseven rows could cover many hours or only a few seconds. The query's final\nordering is another separate choice. The sequence used to compute a running\nvalue does not by itself tell the result consumer how rows will be delivered.\n\n## Why it matters\n\nA common requirement in a report is to see both the number and the reason it\nmoved. A list of sales can display each amount alongside a weekly running total.\nA quality review can show where a reading falls within the results from its own\ndevice. Keeping the original row alongside the calculation lets the reader trace\na change back to the sale, observation or event that contributed to it.\n\nWindow functions make definitions sensitive to the match between the question\nand the input grain. A three-row moving average is useful if each row is a day\nand the dates are complete. If a sensor stops reporting for two days, the same\nexpression can span five calendar days when it reaches across the gap. Choose\nexplicitly whether the report should exclude the absent days, include them as\nunknowns, or represent them with a business-approved replacement such as zero.\nEach policy leads to a different interpretation of the result.\n\nRanking also needs a definition of equality. In a ranking by delivery time,\nidentical times could share a rank even if the resulting sequence has gaps.\nAnother report may need a predictable unique position for every record. Adding a\nstable secondary key can support that case. Take care to keep intended ties\nwhere they matter. The test suite can use rows with matching amounts and missing\ndates to make both decisions visible.\n\n## What it looks like in practice\n\nImagine a daily usage report for several sites. First decide what a daily\nreading means when records arrive from different timezones. Group the events\ninto one row per local date and site and retain a count of contributing events.\nFor a rolling figure that covers calendar days, build a date series explicitly\nand merge the aggregates with it. Then run the window by site, using date for\nits calculation order and an explicit frame. Return the site, date, daily total\nand the window value side by side.\n\nA second column can compare each day with its predecessor. A useful test\nincludes the first day of a series, a date with no readings and two devices\nwhose reporting schedules differ. Check which previous record the expression\nreceives in each case. The first day might have no comparison. For a gap, the\nreport's desired definition tells you whether to compare with the last actual\nreading or with the previous calendar day, even when its value is unknown.\n\nEngineer's\n[reporting-system case study](/portfolio/developed-a-data-analytics-reporting-system/)\ndescribes collecting and analysing data in an automated workflow that produces\nregular PDF reports. A window calculation is one way an illustrative SQL-backed\nreport can support the same need for recurring comparisons. The calculation\nshould have a readable label and a documented grain. If a reader sees a line\nlabelled seven-day average, the implementation and its checks should make it\neasy to establish exactly which seven days contribute.\n\n## Where it goes wrong\n\nAn implicit frame can surprise a query author who expects every displayed row to\nadd one step to a cumulative result. When ordering values have peers, a\nrange-based frame can include those peers together. A running total can appear\nto jump on several rows at once. Specify the desired frame and test tied\ntimestamps. Decide whether a second order key identifies an actual sequence or\nmerely supplies a stable display order.\n\nFiltering can also move the starting point of a calculation. If a report asks\nfor the last seven displayed dates and the first displayed row needs the\npreceding six days, the window needs access to those earlier rows. Compute the\nnecessary history before applying the display filter. A test with known daily\ntotals can show when the beginning of a chart accidentally starts with too\nlittle data.\n\nFinally, measure how the query executes on representative partitions. Sorting a\nlarge workload can consume memory and time, particularly if several window\ndefinitions require different orders. Combine compatible calculations where it\nimproves clarity, and inspect the execution plan with the data size expected in\nproduction. Keep the deterministic input and the expected rows with the query\ntests. These checks make a later change to the grouping stage, timezone policy\nor frame explainable to the people who rely on the report.\n\n## Further reading\n\n- [PostgreSQL window functions](https://www.postgresql.org/docs/18/functions-window.html).\n  Describes functions, peer rows and the treatment of frames.\n- [PostgreSQL window-function tutorial](https://www.postgresql.org/docs/18/tutorial-window.html).\n  Shows the relationship between the OVER clause and rows produced by a query.\n- [SQLite window functions](https://sqlite.org/windowfunctions.html). Documents\n  frame types, boundaries and examples in SQLite.\n\n\u003chttps://engineer.company/glossary/window-function/\u003e\n","date_modified":"2026-11-25T07:18:46Z","description":"Compare running totals and rankings in SQL and see how ordering, partitions and frames change the result.","formats":{"gemtext":"https://engineer.company/glossary/window-function/index.gmi","gopher":"https://engineer.company/glossary/window-function/gophermap","html":"https://engineer.company/glossary/window-function/","json":"https://engineer.company/glossary/window-function/index.json","markdown":"https://engineer.company/glossary/window-function/index.md","pdf":"https://engineer.company/glossary/window-function/index.pdf"},"kind":"page","language":"en","title":"What is a window function?","url":"https://engineer.company/glossary/window-function/","version":1}