Databases & SQL Master Course — 081. Window Function Fundamentals
Lesson 081 Window Function Fundamentals
Prerequisites and objectives
You can aggregate with GROUP BY and compose queries with CTEs. You will now retain individual rows while calculating a related total, distinguish a partition from a grouped result, and explain how filtering changes the rows available to a window calculation. No application code or Python knowledge is needed.
Create the practice fixture
Use a fresh SQLite database with window-function support, introduced in version 3.25.0. Four fictional sales belong to two regions. One amount is unknown, not zero. Monetary values are integer cents in one fictional currency. The examples are read-only and preserve every source row.
CREATE TABLE regional_sales (sale_id INTEGER PRIMARY KEY,region TEXT NOT NULL,amount_cents INTEGER);
INSERT INTO regional_sales VALUES (1,'North',100),(2,'North',300),(3,'South',200),(4,'South',NULL);
Add context without collapsing detail
GROUP BY region would produce one summary row per region. A window aggregate can instead attach the region’s total to each sale row. The OVER clause makes the aggregate operate as a window function. PARTITION BY region defines which rows belong to the same calculation group, while the result still retains sale identity.
There is no window ORDER BY in this first example, so the aggregate uses the whole partition. North’s known amounts total 400 cents and South’s known amount totals 200. The unknown South amount remains NULL in its detail column; SUM ignores that unknown input rather than converting the stored value to zero.
SELECT sale_id,amount_cents,SUM(amount_cents) OVER (PARTITION BY region) AS regional_cents FROM regional_sales ORDER BY sale_id;
| Sale | Amount | Regional total |
|---|---|---|
| 1 | 100 | 400 |
| 2 | 300 | 400 |
| 3 | 200 | 200 |
| 4 | NULL | 200 |
Four rows enter and four detail rows remain. The repeated regional total is context, not an additional sale. Summing that repeated output column would count North’s total twice and South’s total twice. Window functions preserve detail, which means the grain and duplicate-measure cautions from earlier lessons still apply.

Choose the partition deliberately
An empty OVER clause uses all rows supplied to the window as one partition. PARTITION BY region uses one partition per region. Several partition columns describe a more specific grouping, such as region and reporting month. Choose them from the question rather than copying a nearby GROUP BY mechanically.
Window functions add calculations to rows; they do not guarantee the final display order. The outer ORDER BY sale_id makes this teaching result reproducible. Later lessons distinguish calculation order inside OVER from presentation order outside it.
Understand the input boundary
WHERE filters the input rows before this window calculation. If you remove the 100-cent sale first, North’s total becomes 300 rather than 400. If the question asks to display large sales while retaining their full-region context, calculate the window in an inner query and filter its output in an outer query.
This is a semantic choice, not merely a formatting trick. A dashboard can show identical detail rows with different denominators depending on where filtering occurs. Write the intended population in words before calculating percentages or comparing a sale with its regional total.
Respect SQLite’s placement rules
SQLite window expressions belong in the SELECT result or ORDER BY, not directly in WHERE. Use a CTE or derived table when filtering a calculated window result. SQLite also does not support DISTINCT inside a window aggregate, so entity-distinct calculations need an earlier deduplication or another explicit query design.
Do not describe windows as inherently faster than grouped joins. They provide an expressive way to retain detail with aggregate context; performance depends on data, ordering, indexes, and the query plan. This small fixture verifies meaning, not a universal speed advantage.
Four worked exercises
Exercise 1
Attach the total known sales amount across all four rows.
Worked solution
SELECT sale_id,SUM(amount_cents) OVER () AS all_cents FROM regional_sales ORDER BY sale_id;
The all-row total is 600 cents on every detail row. The empty OVER clause has one partition. This repeated value should be displayed as context rather than summed again across the result.
Exercise 2
Count all rows and known amounts within each region.
Worked solution
SELECT sale_id,COUNT(*) OVER (PARTITION BY region),COUNT(amount_cents) OVER (PARTITION BY region) FROM regional_sales ORDER BY sale_id;
Both regions have two rows, but South has only one known amount. COUNT star and COUNT of the amount answer different completeness questions. A NULL amount does not remove the sale row from the partition.
Exercise 3
Filter amounts of at least 200 cents before calculating regional totals.
Worked solution
SELECT sale_id,SUM(amount_cents) OVER (PARTITION BY region) FROM regional_sales WHERE amount_cents>=200 ORDER BY sale_id;
Only sales two and three enter the window. North’s total is therefore 300. The unknown amount does not satisfy the comparison, so it is also excluded by WHERE.
Exercise 4
Display the same large sales but retain totals calculated over the original regional population.
Worked solution
WITH context AS (SELECT sale_id,amount_cents,SUM(amount_cents) OVER (PARTITION BY region) AS regional_cents FROM regional_sales) SELECT sale_id,regional_cents FROM context WHERE amount_cents>=200 ORDER BY sale_id;
North’s displayed context is now 400 because the inner query includes its 100-cent sale. The outer filter changes presentation without changing the earlier calculation population. This pattern becomes important for rankings and running balances.
Knowledge check
Question 1
What distinguishes SUM as a window aggregate here?
- The presence of a primary key
- The final ORDER BY alone
- The OVER clause
- Using an integer column
Answer and explanation
C. OVER defines the window context while retaining detail rows.
Question 2
How many detail rows remain in the first result?
- Two, one per region
- Four
- One, one grand total
- Three, because NULL is discarded entirely
Answer and explanation
B. The unknown amount stays as a detail row even though SUM ignores its value.
Question 3
What does WHERE affect before a window calculation?
- Which rows enter the calculation
- Only which already-computed window rows are displayed
- Only rows that the outer ORDER BY places first
- Nothing until after every window finishes
Answer and explanation
A. Filter placement changes the population available to the window.
Question 4
How can large sales retain full regional totals?
- Add DISTINCT to every SUM OVER
- Remove PARTITION BY and assume totals stay regional
- Sum the displayed regional totals again
- Calculate totals inside a CTE, then filter outside
Answer and explanation
D. The outer filter operates after the inner context has been computed.
Question 5
Why avoid summing repeated regional totals?
- Regional sums ignore duplicate detail rows automatically
- They repeat the same regional fact on several detail rows
- A later SUM always collapses equal totals to one value
- Every region has exactly one sale
Answer and explanation
B. Preserved detail can duplicate higher-grain measures in the output.
Pitfalls and summary
Do not confuse retained detail with grouped output or let a filter silently change the intended denominator. Declare the partition and input population, keep final ordering explicit, and interpret repeated aggregates at their proper grain. Windows add context to rows; they do not remove the need to reason about those rows.
SQLite behavior and references
Examples were checked with SQLite 3.53.1 on 10 October 2026. Use a SQLite SQL editor; Python is not a prerequisite. Verify dialect-specific functions, comparison rules, and numeric behavior before moving the examples to another engine.
Primary references
- SQLite window functions: Partitions, ordering, frames, and built-in functions
- SQLite SELECT: Query stages and final ordering