- Learn
- Computer Science & IT
- Programming
- Database Design and Advanced SQL
- SQL Window Functions
SQL Window Functions and Analytical Queries
OVER, PARTITION BY and ORDER BY: rank and number rows, keep the top rows of each group, build running totals and moving averages with window frames, and compare each row with earlier, later or reference rows using LAG, LEAD and FIRST_VALUE. Worked examples on small sales and staff tables show every result step by step, along with the classic mistakes around ties, default frames and filtering.IntermediateLesson 2 of 8 in Database Design and Advanced SQL Course
What you will learn
- Use the
OVERclause to calculate across related rows while keeping every row, and place window functions correctly in a query.- Compare window functions with GROUP BY aggregatesSee how a window function returns a value on every row, and decide when to use it instead of
GROUP BY. - Divide and order rows with PARTITION BY and ORDER BYSplit rows into partitions, set the processing order inside each partition, handle NULLs in that order and reuse a window definition with the
WINDOWclause. - Place window functions correctly in a queryUse the logical order of query processing to know where window functions are allowed, how to filter on their results and how they combine with
GROUP BY.
- Compare window functions with GROUP BY aggregates
- Number, rank and bucket rows within groups, handle ties deliberately and keep the top rows of each group.
- Number and rank rows with ROW_NUMBER, RANK and DENSE_RANKApply the three main ranking functions, predict how each one treats ties and choose the one that matches the question.
- Split rows into buckets and percentiles with NTILE, PERCENT_RANK and CUME_DISTDivide ordered rows into equal-sized groups and express each row's position as a fraction of its partition.
- Keep the top N rows of each group and remove duplicatesCombine a ranking function with an outer filter to keep the best rows per group, decide how ties count and delete duplicate rows.
- Number and rank rows with ROW_NUMBER, RANK and DENSE_RANK
- Build cumulative and rolling calculations, and control exactly which rows each calculation uses with a frame clause.
- Build running totals and other cumulative valuesCalculate running totals, counts, maximums and averages that restart per group or period, and handle ties and NULLs correctly.
- Control the window frame with ROWS, RANGE and GROUPSWrite frame clauses that choose exactly which rows around the current row a calculation uses, and know the default frame and its effects.
- Calculate moving averagesSmooth a series with row-based and time-based rolling windows, and deal with the first rows, missing dates and integer averages.
- Build running totals and other cumulative values
- Reach other rows of the window to measure change, compare with reference rows and find streaks and gaps in ordered data.
- Look back and ahead with LAG and LEADFetch values from earlier and later rows to calculate differences, growth rates and time between events.
- Pick the first, last or nth value of a windowUse
FIRST_VALUE,LAST_VALUEandNTH_VALUEto compare each row with a reference row, and set the frame so they return what you expect. - Detect changes, streaks and gapsFlag rows where a value changes, group consecutive rows into streaks (gaps and islands) and measure each streak and gap.
- Look back and ahead with LAG and LEAD
- Combine aggregation, window functions and CTEs into multi-step reports, and check that the results are correct, portable and fast enough.
- Combine windows, aggregates and CTEs into a reportAnswer multi-step questions by aggregating to the right level, applying windows to the grouped rows and layering the steps with CTEs.
- Check correctness, portability and performanceMake window queries repeatable and correct, know the main differences between database systems and keep the queries efficient.
- Combine windows, aggregates and CTEs into a report
SQL Window Functions study guide
1Explain what window functions compute
An employee can have a salary, a department average and a rank on the same output row. Window functions make that combination possible. Start by choosing the shape of the answer, then define which rows belong together and how to order them. The placement of a filter matters just as much as the calculation: removing rows before a window can change every result, while removing them afterward can preserve the full comparison.
1.1 Compare window functions with GROUP BY aggregates
A window function calculates a value using related rows and places the answer alongside each current row. The call ends with OVER (...). Adding a window column does not itself merge rows, so names, dates and other detail can remain visible.
Choose the output shape
Consider employees(name, dept, salary):
| Department | Employees and salaries |
|---|---|
| Sales | Ana 4200; Ben 3900; Chen 4200; Dev 3500 |
| IT | Eva 5100; Femi 4800; Gus 5100; Hana 4500; Ivo 4000 |
A grouped query answers "What is the average salary in each department?"
SELECT dept, AVG(salary) AS dept_avg
FROM employees
GROUP BY dept;
Its two output rows are Sales 3950 and IT 4700. Each row represents a department. Employee names no longer have a single value within that row.
A different question is "How far is each person's salary from the department average?" Each output row now needs to represent one employee:
SELECT name, dept, salary,
AVG(salary) OVER (PARTITION BY dept) AS dept_avg,
salary - AVG(salary) OVER (PARTITION BY dept) AS diff
FROM employees
ORDER BY dept, name;
There are nine output rows. Ana's department values are 4200, 3900, 4200 and 3500. Their total is 15800, and dividing by four gives 3950. Ana's difference is 250; Dev's is -450. In IT the total is 23500 across five people, so Eva is 400 above the average of 4700 and Ivo is 700 below it.
Read OVER as the calculation's scope
PARTITION BY dept gives each employee access to the employees in the same department. It does not remove the employee rows or require a join. Without a partition clause, OVER () uses all rows available at the window stage:
SELECT name, salary,
COUNT(*) OVER () AS people,
AVG(salary) OVER () AS overall_avg
FROM employees;
Every row shows a count of 9 and an overall average of about 4366.67, from the total salary of 39300. This can answer a different comparison from the department average. Neither average requires replacing the name with a group label.
Recognize the two function families
| Family | Examples | Role of OVER |
|---|---|---|
| Ordinary aggregates | SUM, AVG, COUNT, MIN, MAX | Turns the aggregate into a window calculation |
| Dedicated window functions | ROW_NUMBER, RANK, LAG, FIRST_VALUE | Required as part of the function call |
AVG(salary) without OVER is an ordinary aggregate. ROW_NUMBER() cannot be called without OVER. A join to a grouped department table or a correlated subquery can produce the same department comparison; the window expression states that comparison directly.
If you need only the employees above their department average, the window calculation alone will still return everyone. Compute the average first, then use an outer query to keep the required employees. Row reduction is a separate query step.
Key Takeaways
- GROUP BY produces one row per group; a window calculation adds a result to each available row.
OVER ()uses the whole set of rows at the window stage.PARTITION BY deptgives each employee a department comparison.- An aggregate becomes a window function when followed by
OVER; dedicated window functions require it.
1.2 Divide and order rows with PARTITION BY and ORDER BY
A window definition answers two separate questions: "Which rows belong with this row?" and "In what order should they be considered?" Put the clauses in the order PARTITION BY, ORDER BY, then the frame when one is needed.
Start again inside each partition
The sales examples use daily_sales(store, sale_date, units), with one row per store and recorded date in March 2026:
| Store | Day and units |
|---|---|
| North | 01: 10; 02: 14; 03: 9; 04: 15; 06: 12; 07: 16 |
| South | 01: 8; 02: 11; 03: 11; 04: 7; 05: 13 |
North has no row for March 5. The store totals are 76 and 50.
SELECT store, sale_date, units,
ROW_NUMBER() OVER (
PARTITION BY store ORDER BY sale_date
) AS day_number
FROM daily_sales
ORDER BY store, sale_date;
North receives numbers 1 through 6, and South starts again at 1 and ends at 5. With no PARTITION BY, all eleven rows share one partition. A partition can use several expressions: PARTITION BY store, EXTRACT(YEAR FROM sale_date) in PostgreSQL creates separate store-year groups.
Keep the two orders separate
The ORDER BY inside OVER controls the calculation. The final ORDER BY controls display. You can number days chronologically and display the finished report in reverse date order without changing the assigned numbers.
Order also affects aggregate windows. SUM(units) OVER (PARTITION BY store) shows 76 on every North row. Adding ORDER BY sale_date gives cumulative values 10, 24, 33, 48, 60 and 76. The default frame then reaches from the partition's start through the current row and any peers.
Peers have equal values in every window sort expression. South's two 11-unit days are peers under ORDER BY units, but they are different positions under ORDER BY sale_date. RANK and DENSE_RANK preserve ties; ROW_NUMBER gives separate numbers, and NTILE can split a tie across buckets.
Reuse a definition
SELECT store, sale_date,
SUM(units) OVER w AS running_units,
ROW_NUMBER() OVER w AS day_number
FROM daily_sales
WINDOW w AS (PARTITION BY store ORDER BY sale_date)
ORDER BY store, sale_date;
The named WINDOW clause follows HAVING, if present, and precedes the final ORDER BY. PostgreSQL, MySQL 8 and SQLite support it. SQL Server supports it from 2022 with database compatibility level 160 or higher.
Check group boundaries and missing sort values
LAG(units) OVER (ORDER BY store, sale_date) crosses stores: South's first day receives North's last value, 16. Partitioning by store gives South's first day no predecessor.
NULL ordering depends on the system. PostgreSQL puts NULL first for descending order. For a highest-score ranking, use ORDER BY score DESC NULLS LAST when missing scores belong at the end. PostgreSQL and SQLite support this syntax; MySQL and SQL Server need another expression or a suitable filter.
Key Takeaways
PARTITION BYsets the boundaries where calculations restart.- The window order controls calculation; the final order controls display.
- Peers tie on every expression in the window order.
- A named window lets several functions share the same definition.
- Check NULL ordering when missing values enter a ranking.
1.3 Place window functions correctly in a query
The location of a calculation or filter changes which rows it can see. Window functions operate after row filtering and grouping. A later query can then filter their results.
Follow the logical order
The useful sequence is FROM and joins, WHERE, GROUP BY, HAVING, window calculations, the finished select list and DISTINCT, final ORDER BY, then LIMIT or FETCH. This describes the query's meaning; the optimizer can use a different physical plan.
A window function can appear in the select list or final ORDER BY. It cannot appear in WHERE, GROUP BY or HAVING in the portable pattern. Those stages happen before its result exists. Referring to its new alias in the same query's WHERE has the same problem.
WITH ranked AS (
SELECT name, dept, salary,
RANK() OVER (ORDER BY salary DESC) AS salary_rank
FROM employees
)
SELECT name, dept, salary
FROM ranked
WHERE salary_rank <= 3
ORDER BY salary_rank, name;
The inner query ranks all nine employees. The outer one keeps Eva and Gus at rank 1 and Femi at rank 3. Snowflake, BigQuery, DuckDB and Teradata also offer QUALIFY for filtering window results directly. The CTE pattern works in PostgreSQL, MySQL, SQL Server and SQLite.
Decide whether earlier rows still count
North's cumulative units are 10, 24, 33, 48, 60 and 76. Putting sale_date >= '2026-03-03' in the same query as the window removes the earlier days first. The displayed totals become 9, 24, 36 and 52.
To show only later days while retaining the accumulated history:
WITH totals AS (
SELECT store, sale_date,
SUM(units) OVER (
PARTITION BY store ORDER BY sale_date
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS running_units
FROM daily_sales
)
SELECT store, sale_date, running_units
FROM totals
WHERE store = 'North' AND sale_date >= '2026-03-03'
ORDER BY sale_date;
Now the results are 33, 48, 60 and 76. A store filter could safely go inside because it removes whole independent partitions; a date cutoff would remove required history.
Apply windows to grouped rows
SELECT store, SUM(units) AS total,
SUM(SUM(units)) OVER () AS grand_total,
RANK() OVER (ORDER BY SUM(units) DESC) AS store_rank
FROM daily_sales
GROUP BY store;
The grouped rows hold totals 76 and 50. The window sum adds those two totals to 126, and the ranks are 1 and 2. The inner SUM aggregates source rows; the outer SUM ... OVER analyzes the grouped result. Bare units is not available at that grain.
DISTINCT runs after windows: SELECT DISTINCT dept, COUNT(*) OVER (PARTITION BY dept) first gives all employees counts, then reduces the output to IT 5 and Sales 4. Windows themselves cannot be nested; calculate one in a CTE before using another window over its result. A subquery can likewise supply window-derived row IDs to an UPDATE or DELETE.
Key Takeaways
- Windows see rows left by
WHERE,GROUP BYandHAVING. - Compute a window result in a CTE before filtering on it.
- Keep historical rows inside the window query when later rows need them.
- After grouping, windows operate on group rows and their aggregates.
- Use separate query layers for dependent window calculations.
DISTINCTcan reduce rows after window values have been calculated.
2Rank and number rows
A position can mean one row, a competition place or a distinct value. Choosing the right ranking function makes that meaning explicit, especially when values tie. You will work from small ordered lists to per-group selections, then use the same pattern to find the latest record and identify duplicates. Distribution functions add another view: they describe where a row sits in an ordered population, with tie behavior that matters at a cutoff.
2.1 Number and rank rows with ROW_NUMBER, RANK and DENSE_RANK
Ranking functions attach positions to rows in a chosen order. The three main functions differ at ties, so start with what a position should mean in the report.
Trace a tie by hand
For IT, order salaries from highest to lowest:
| Name | Salary | ROW_NUMBER | RANK | DENSE_RANK |
|---|---|---|---|---|
| Eva | 5100 | 1 | 1 | 1 |
| Gus | 5100 | 2 | 1 | 1 |
| Femi | 4800 | 3 | 3 | 2 |
| Hana | 4500 | 4 | 4 | 3 |
| Ivo | 4000 | 5 | 5 | 4 |
The displayed row numbers put Eva before Gus. With salary as the only sort expression, their row numbers could be exchanged.
ROW_NUMBER() counts rows, assigning a distinct number to each. RANK() gives a row one plus the number of rows strictly ahead of it. Two people occupy first place, so the next competition rank is 3. DENSE_RANK() counts peer groups: the two 5100 salaries form one level, and 4800 is the second level.
SELECT name, salary,
ROW_NUMBER() OVER (ORDER BY salary DESC, name) AS rn,
RANK() OVER (ORDER BY salary DESC) AS place,
DENSE_RANK() OVER (ORDER BY salary DESC) AS salary_level
FROM employees
WHERE dept = 'IT'
ORDER BY salary DESC, name;
Each function has its own OVER. This lets the row numbers have a repeatable order while the ranks still express salary ties. Employee names are unique in this sample; a primary key is a safer tie-breaker for real data where names can repeat.
Match the function to the question
| Question | Function | What the position counts |
|---|---|---|
| Which single row is first? | ROW_NUMBER | Individual rows |
| Who is joint first, then third? | RANK | Competition places |
| Who has the second-highest distinct salary? | DENSE_RANK | Salary levels |
Femi has the second-highest distinct IT salary even though her competition rank is 3. A filter for RANK() = 2 would find nobody in IT.
Control direction and ties
Ascending order is the default. ORDER BY salary puts the lowest salary at rank 1; ORDER BY salary DESC puts the highest first. Add PARTITION BY dept to restart within each department. Sales then has salary ranks 1, 1, 3 and 4.
A unique tie-breaker changes peer groups. RANK() OVER (ORDER BY salary DESC, employee_id) separates equal salaries when employee IDs differ. Keep the ID in a row-number window when exactly one row must win; leave it out of a salary-ranking window when equal salaries must share a place. Use a final query order to display tied names predictably without changing their ranks.
These three functions take no arguments and rank across the partition, independent of a frame. PostgreSQL allows RANK() OVER (), but with no order every row is a peer and gets rank 1. SQL Server requires a window order. As a check, the largest row number is the partition's row count, and the largest dense rank is its number of distinct sort-value combinations.
Key Takeaways
ROW_NUMBERnumbers rows;RANKleaves gaps after ties;DENSE_RANKcounts distinct levels.- Use descending order when the highest value should lead.
- A unique tie-breaker stabilizes row numbers but also breaks ranking ties if added to their window.
- Partition the ranking when positions must restart for each group.
2.2 Split rows into buckets and percentiles with NTILE, PERCENT_RANK and CUME_DIST
A report may need a row's share of the ordered population, or a bucket containing a similar number of rows to the other buckets. These are position-based calculations. They do not measure a value's share of the total amount.
Divide rows into buckets
NTILE(n) assigns bucket numbers from 1 to n in window order. Bucket sizes differ by at most one; the earlier buckets get the extra rows. With ten rows and four buckets, the sizes are 3, 3, 2 and 2.
SELECT name, salary,
NTILE(2) OVER (ORDER BY salary DESC, name) AS half
FROM employees
WHERE dept = 'IT'
ORDER BY salary DESC, name;
The five IT rows receive 1, 1, 1, 2 and 2. Ties can cross bucket boundaries: with NTILE(5), Eva and Gus occupy separate buckets even though both earn 5100. Use a unique order when the row assignment must be repeatable.
With three rows and four requested buckets, the assigned buckets are 1, 2 and 3. The fourth remains empty. Four row buckets are often called quartile groups, but they do not calculate the statistical values marking quartiles.
Compare two relative positions
For IT in descending salary order:
| Name | RANK | PERCENT_RANK | CUME_DIST |
|---|---|---|---|
| Eva | 1 | 0 | 0.4 |
| Gus | 1 | 0 | 0.4 |
| Femi | 3 | 0.5 | 0.6 |
| Hana | 4 | 0.75 | 0.8 |
| Ivo | 5 | 1 | 1 |
PERCENT_RANK() uses the competition rank:
For Femi, rank 3 among five people gives 2 divided by 4, or 0.5. The first rank has value 0, and a one-row partition also returns 0. A tie at the final rank can keep the largest result below 1.
CUME_DIST() divides the number of rows ahead of or tied with the current row by the partition's row count. Eva and Gus jointly account for two of five rows, giving 0.4 each. Femi's 0.6 means 60% earn at least her salary in this descending order. The final peer group reaches 1.
Inspect a percentage cutoff
Suppose 50 customers are ordered by spending, highest first. Filtering a computed CUME_DIST at 0.10 can retain the first five rows when the boundary has no tie. If positions five and six tie, both have cumulative distribution 0.12 and both fail the cutoff. Only the first four remain.
That rule keeps peer groups whose cumulative population stays within 10%. It is different from keeping exactly five customers or including every customer tied with fifth place. Choose ROW_NUMBER for a fixed row count and a ranking rule for a tie-inclusive boundary. Neither a relative rank of 0.5 nor a bucket number says that someone's salary is half the salary total.
Key Takeaways
NTILEbalances row counts and can split equal values.PERCENT_RANKis(rank - 1) / (row count - 1), with 0 for one row.CUME_DISTincludes the current row and all its peers in its numerator.- Relative position is different from share of a measure total.
- Check ties at distribution cutoffs; they can change the number retained.
2.3 Keep the top N rows of each group and remove duplicates
Top N per group means a separate selection inside every group. A global LIMIT 2 keeps two rows from the entire final result, so it cannot supply two employees from each department.
Rank first, filter second
WITH ranked AS (
SELECT name, dept, salary,
ROW_NUMBER() OVER (
PARTITION BY dept ORDER BY salary DESC, name
) AS rn
FROM employees
)
SELECT dept, name, salary
FROM ranked
WHERE rn <= 2
ORDER BY dept, salary DESC, name;
The CTE assigns positions inside each department. The filter keeps Eva and Gus in IT and Ana and Chen in Sales. The sample names break ties; use a unique key when names are not unique. Groups with fewer than two rows return their available rows.
Decide what N counts
| Selection rule | Window order | Effect of a salary tie |
|---|---|---|
ROW_NUMBER <= 2 | Salary descending, then unique ID | Keeps at most two rows |
RANK <= 2 | Salary descending | Keeps all rows at competition places 1 or 2 |
DENSE_RANK <= 2 | Salary descending | Keeps everyone at the top two salary levels |
With the sample data, RANK <= 2 keeps the two joint leaders in each department. The next competition rank is 3. DENSE_RANK <= 2 also keeps Femi and Ben, who occupy the second salary levels. Keep the unique ID out of the latter two windows when ties should remain tied.
A condition such as "active employees only" belongs inside the ranked CTE if positions should be assigned among active people. If inactive employees receive positions first, removing them later can leave gaps and too few active employees.
Keep the whole latest row
For orders(customer_id, order_id, order_date, amount), use:
ROW_NUMBER() OVER (
PARTITION BY customer_id
ORDER BY order_date DESC, order_id DESC
)
An outer filter for row number 1 returns the latest complete order per customer, with the highest order ID winning equal dates. MAX(order_date) alone finds a date; it does not select the other fields belonging to that order.
Identify duplicates using the same pattern
For customers(customer_id, email, updated_at), partition by email and order by updated_at DESC, customer_id DESC. Records 1 and 2 have email 'a@x.org', updated on January 5 and February 10, 2026; record 3 has 'b@x.org', updated January 20. Record 2 gets row number 1 for its email, record 1 gets 2, and record 3 gets 1.
In PostgreSQL, delete by IDs supplied from the ranking subquery:
DELETE FROM customers
WHERE customer_id IN (
SELECT customer_id
FROM (
SELECT customer_id,
ROW_NUMBER() OVER (
PARTITION BY email
ORDER BY updated_at DESC, customer_id DESC
) AS rn
FROM customers
) AS numbered
WHERE rn > 1
);
Run the inner selection first to inspect which records will be removed. Here only record 1 is selected for deletion.
A per-group lateral subquery is another approach: PostgreSQL uses LATERAL with an ordered limit; SQL Server uses CROSS APPLY with TOP. Such plans can help with few groups and a matching index. The partitioned-window pattern directly expresses the general selection rule.
Key Takeaways
- Partition the ranking by the group, then filter its result in an outer query.
- Choose whether N counts rows, competition places or distinct values.
- Filter eligible source rows before assigning positions among them.
- The latest-row pattern keeps all columns from one chosen record.
- Deduplication partitions by the duplicate key and orders by which record should survive.
- Inspect selected duplicate IDs before deleting them.
3Compute running totals and moving averages with window frames
A running total needs a starting boundary; a moving average needs a sliding boundary. A window frame supplies both. Work through order-level and date-level totals, then compare frames that count rows, value distances or peer groups. Missing dates and NULL measures deserve particular care because a three-row average can cover more than three days and can use fewer than three values. Explicit frames make those choices visible in the query.
3.1 Build running totals and other cumulative values
A running total adds the current measure to the measures that precede it in a chosen order. Four decisions define it: the partition, the order, the measure and the frame.
Build one cumulative column
For North, recorded units in date order are 10, 14, 9, 15, 12 and 16.
SELECT store, sale_date, units,
SUM(units) OVER (
PARTITION BY store ORDER BY sale_date
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS running_units
FROM daily_sales
ORDER BY store, sale_date;
The first frame contains 10. The next contains 10 and 14, giving 24. The third adds 9, giving 33. The remaining totals are 48, 60 and 76. South starts again with 8 and continues to 19, 30, 37 and 50. The last total in each partition matches its grouped total.
Replace SUM with another aggregate to ask a related question. North's running COUNT(*) is 1 through 6. Its running maximum is 10, 14, 14, 15, 15 and 16. Its running average is 10, 12, 11, 12, 12 and about 12.67. Every row adds another observation to the calculation, even when the maximum stays unchanged.
Choose what a tie means
The orders sample contains these rows:
| Order ID | Date in March 2026 | Amount |
|---|---|---|
| 1 | 01 | 50 |
| 2 | 01 | 30 |
| 3 | 02 | 20 |
| 4 | 03 | 40 |
SUM(amount) OVER (ORDER BY order_date) uses the default frame, which includes all current peers. Both March 1 rows therefore show 80, followed by 100 and 140. The result means "total through this date."
For "total through this order," use ORDER BY order_date, order_id and the explicit ROWS frame shown above. The totals become 50, 80, 100 and 140. Without the tie-breaker, a row-based calculation has no stable first March 1 order.
For one output row per day, group first:
SELECT order_date,
SUM(SUM(amount)) OVER (ORDER BY order_date) AS running_amount
FROM orders
GROUP BY order_date
ORDER BY order_date;
The daily result is 80, 100 and 140.
Move the reset or the boundary
A year-to-date total restarts with the year. In PostgreSQL, partition by EXTRACT(YEAR FROM order_date), adding the store or account key when each entity needs its own total. For month-to-date totals, include both year and month so different years stay separate.
A frame from CURRENT ROW to UNBOUNDED FOLLOWING totals what remains, including the current order. With the unique order above, the results are 140, 90, 60 and 40.
Aggregates skip NULL measures. A cumulative SUM is NULL while every amount in the frame is NULL, then remains unchanged when a later NULL arrives. COUNT(*) counts those rows; COUNT(amount) counts only known amounts. Use COALESCE to replace NULL with zero only when that is the correct meaning of the data.
A correlated subquery that sums all dates less than or equal to the current date gives the peer-inclusive total too. It can repeatedly scan earlier rows; an ordered window often gives the database a more efficient plan.
Key Takeaways
- A running calculation needs a partition, order, measure and frame.
- An explicit
ROWSframe and unique order give a repeatable total through each individual row. - The default ordered frame includes the current peer group.
- Period expressions in
PARTITION BYcontrol resets. COUNT(*)counts rows; measure aggregates skip NULL values.
3.2 Control the window frame with ROWS, RANGE and GROUPS
A frame is the part of a partition available to a frame-sensitive function for the current row. Aggregates and FIRST_VALUE, LAST_VALUE and NTH_VALUE use it. Ranking functions and LAG or LEAD use partition positions independently of the frame.
Read the distance unit
| Mode | What the distance counts | Example ending at CURRENT ROW |
|---|---|---|
ROWS | Individual ordered rows | 2 PRECEDING includes at most three rows |
RANGE | Distance in the sort value | 2 PRECEDING in ascending numeric order includes values from current minus 2 through current |
GROUPS | Peer groups | 1 PRECEDING includes the preceding and current peer groups |
With descending numeric order, a RANGE preceding bound reaches toward larger values. At value 8, RANGE BETWEEN 2 PRECEDING AND CURRENT ROW covers values from 8 through 10. An offset RANGE needs a single suitable sort expression; PostgreSQL date ranges use an interval such as INTERVAL '2 days'.
Write the bounds
The full form is ROWS, RANGE or GROUPS, followed by BETWEEN start AND end. Bounds are ordered by type:
UNBOUNDED PRECEDING- An offset
PRECEDING CURRENT ROW- An offset
FOLLOWING UNBOUNDED FOLLOWING
The start cannot be UNBOUNDED FOLLOWING; the end cannot be UNBOUNDED PRECEDING or an earlier bound type than the start. Thus BETWEEN CURRENT ROW AND 2 PRECEDING is invalid. In PostgreSQL, two bounds of the same offset type can define an empty frame: ROWS BETWEEN 7 PRECEDING AND 8 PRECEDING is accepted and contains no rows. ROWS 2 PRECEDING is shorthand for ending at CURRENT ROW.
Trace peer groups
Use the four orders: March 1 amounts 50 and 30, March 2 amount 20, March 3 amount 40.
| Sum frame, ordered by date | Results in order |
|---|---|
| Default ordered frame | 80; 80; 100; 140 |
Cumulative ROWS, adding order ID to the order | 50; 80; 100; 140 |
GROUPS BETWEEN 1 PRECEDING AND CURRENT ROW | 80; 80; 100; 60 |
For March 3, the last frame includes the March 2 and March 3 peer groups, so the total is 60. CURRENT ROW in RANGE or GROUPS reaches the relevant boundary of the whole peer group. In ROWS, it refers to the individual row.
With a window order and no explicit frame, the default is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. With no window order, the default covers the whole partition.
Exclude rows after defining the frame
PostgreSQL and SQLite support EXCLUDE CURRENT ROW, EXCLUDE GROUP, EXCLUDE TIES and EXCLUDE NO OTHERS. They remove, respectively, the current row; the current row and peers; only the other peers; or nothing.
A full-department salary average with EXCLUDE CURRENT ROW compares someone with their colleagues. For Ana, remove 4200 from Sales' 15800, then average the remaining 11600 over three people: about 3866.67.
ROWS frames have broad support. PostgreSQL and SQLite also support GROUPS and exclusion. MySQL 8 supports ROWS and offset RANGE, but not GROUPS or exclusion. SQL Server's RANGE bounds are limited to UNBOUNDED and CURRENT ROW.
Key Takeaways
ROWScounts rows,RANGEmeasures sort-value distance, andGROUPScounts peer groups.- The default ordered frame reaches through the current row's last peer.
- Frame bounds use positions relative to the current row or group.
EXCLUDE TIESkeeps the current row;EXCLUDE GROUPremoves it with its peers.- Ranking and offset functions do not use the frame.
- Check dialect support before using offset
RANGE,GROUPSor frame exclusion.
3.3 Calculate moving averages
A moving average averages a bounded set of nearby observations as that set slides through a series. It smooths short-term variation without averaging the entire history.
Work through a trailing average
SELECT sale_date, units,
AVG(units) OVER (
ORDER BY sale_date
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
) AS ma3
FROM daily_sales
WHERE store = 'North'
ORDER BY sale_date;
North's units are 10, 14, 9, 15, 12 and 16. The results are 10, 12, 11, about 12.67, 12 and about 14.33. On March 4, the frame contains 14, 9 and 15: total 38 divided by 3. On March 7, it contains 15, 12 and 16: total 43 divided by 3.
The current row counts toward the size. A three-row average uses 2 PRECEDING; a seven-row average uses 6 PRECEDING. A running average uses an unbounded start and keeps growing, so it answers a different question.
Decide what to show at the start
The first row has no predecessors and the second has only one. AVG uses the available values, so early results need not be full-size averages. To show only full three-row frames:
SELECT sale_date,
CASE WHEN COUNT(*) OVER w = 3
THEN AVG(units) OVER w END AS ma3
FROM daily_sales
WHERE store = 'North'
WINDOW w AS (
ORDER BY sale_date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
)
ORDER BY sale_date;
The first two results become NULL. If three known measures are required, test COUNT(units) instead, because a frame can hold three rows but only two non-NULL values.
Distinguish rows from days
North has no March 5 row. The three-row frame on March 6 includes March 3, 4 and 6, spanning four calendar days. In PostgreSQL, a trailing three-calendar-day frame uses:
AVG(units) OVER (
PARTITION BY store ORDER BY sale_date
RANGE BETWEEN INTERVAL '2 days' PRECEDING AND CURRENT ROW
)
At March 6, it includes only March 4 and March 6, averaging 15 and 12 to 13.5. At March 7, it averages 12 and 16 to 14. The interval chooses dates; it does not create a missing observation.
If the missing date means zero sales, join to a calendar and fill that date with zero. March 4–6 then averages 15, 0 and 12 to 9. If the date means an unknown amount, filling it with zero would change the meaning of the report.
Look on both sides when appropriate
A centered three-row frame is ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING. North's results are 12, 11, about 12.67, 12, about 14.33 and 14. The edge frames are shorter. A full centered value for the latest observation requires a future observation, so it is suitable for retrospective analysis.
Partition moving calculations by store or sensor to stop frames crossing groups. The same frame works with SUM, MIN and MAX. In SQL Server, cast integer inputs before AVG, for example AVG(CAST(units AS decimal(10,2))), to preserve fractional averages.
Key Takeaways
- A trailing N-row average includes the current row and N minus one predecessors.
- Use the count over the same frame to detect incomplete averages.
ROWSfollows observations; an intervalRANGEfollows calendar distance.- Fill missing dates with zero only when missing means zero.
- Centered frames require following observations for a full result.
- Cast integer inputs before averaging in SQL Server to keep fractions.
4Compare rows with LAG, LEAD and value functions
A row becomes more informative when you can compare it with a neighbor or a reference point. LAG and LEAD retrieve earlier and later observations; positional value functions retrieve values from frame boundaries. Those comparisons lead to growth rates, changes in status, login streaks and event sessions. Keep the row order explicit throughout: a previous observation is not always yesterday, and the last value in a frame is not always the last value in a partition.
4.1 Look back and ahead with LAG and LEAD
LAG retrieves a value from an earlier row in the window order. LEAD retrieves one from a later row. Their arguments are the expression, an optional row offset and an optional default for an out-of-bounds position.
Retrieve neighbors before calculating change
SELECT sale_date, units,
LAG(units) OVER w AS previous_units,
LEAD(units) OVER w AS next_units
FROM daily_sales
WHERE store = 'North'
WINDOW w AS (ORDER BY sale_date)
ORDER BY sale_date;
The offset defaults to 1 and the missing-position default to NULL. North's units 10, 14, 9, 15, 12 and 16 have previous values NULL, 10, 14, 9, 15 and 12. Their next values are 14, 9, 15, 12, 16 and NULL. Subtracting the previous value gives changes NULL, 4, -5, 6, -3 and 4.
For several stores, add PARTITION BY store. Otherwise the first row of a new store can inherit the last observation of another store. A unique order is also needed when several observations share a timestamp.
Use the previous value as the growth denominator
Monthly revenues 200, 250, 225 and 270 produce percentage changes NULL, 25, -10 and 20. The March decrease is 25 relative to February's 250.
WITH previous AS (
SELECT month_start, revenue,
LAG(revenue) OVER (ORDER BY month_start) AS prev_revenue
FROM monthly_revenue
)
SELECT month_start, revenue,
(revenue - prev_revenue) * 100.0
/ NULLIF(prev_revenue, 0) AS pct_change
FROM previous
ORDER BY month_start;
100.0 preserves fractional division where integer division would truncate. NULLIF changes a zero denominator to NULL. An absent predecessor also leaves growth NULL. LAG(revenue, 1, 0) would manufacture a zero starting comparison when there is no earlier row; use it only when that starting value has an intended meaning. A default does not replace a NULL value stored in an existing predecessor row.
Count observations and elapsed time separately
LAG(revenue, 12) means twelve rows earlier. It means the same month last year only if the series has exactly one row for every month. Select LAG(month_start, 12) as well when checking that relationship.
North's March 6 predecessor is March 4. In PostgreSQL, subtracting dates gives 2 days:
sale_date - LAG(sale_date) OVER (
PARTITION BY store ORDER BY sale_date
)
Timestamp subtraction gives an interval. The date comparison reveals the missing March 5 observation even though the two rows are adjacent.
To find declines, compute prev_units in a CTE and filter units < prev_units outside. North then returns March 3 and March 6. Filtering earlier would change the predecessor sequence.
LAG and LEAD ignore the frame: a one-row frame does not stop them reaching a neighboring partition row. NULL skipping is dialect-specific. PostgreSQL 18 and MySQL 8.4 use the ordinary behavior that respects NULLs; SQL Server 2022 and Oracle support IGNORE NULLS. A running non-NULL count followed by a second query stage can group rows for a last-known-value calculation where that syntax is unavailable.
Key Takeaways
LAGlooks back andLEADlooks ahead by a row offset, defaulting to one.- The default argument handles an absent row, not a NULL stored in an existing row.
- Percent change divides the difference by the previous value; protect a zero denominator.
- A row offset is a time offset only when the series has the required complete spacing.
- Offset functions respect partition boundaries and ignore the frame.
4.2 Pick the first, last or nth value of a window
FIRST_VALUE, LAST_VALUE and NTH_VALUE retrieve a column from a position within the current frame. The frame is the crucial difference from LAG and LEAD, which follow offsets across the partition.
Compare with a starting value
SELECT name, salary,
salary - FIRST_VALUE(salary) OVER (
PARTITION BY dept ORDER BY salary DESC
) AS diff_from_top
FROM employees
ORDER BY dept, salary DESC, name;
The first IT salary is 5100. The differences for Eva, Gus, Femi, Hana and Ivo are 0, 0, -300, -600 and -1100. Although the first two rows tie, the retrieved salary is the same. Retrieving a name is different: add a unique tie-breaker so the top person's identity is repeatable.
In the sample, FIRST_VALUE(name) OVER (PARTITION BY dept ORDER BY salary DESC, name) picks Eva throughout IT. Real tables can have duplicate names, so use a unique employee key as the final sort expression.
Widen the frame for the final value
With descending salary and then name, the default ordered frame ends at the current row. LAST_VALUE(name) therefore returns Eva, Gus, Femi, Hana and Ivo on their own rows. It has reached the last row of each growing frame, not the end of IT.
SELECT name, salary,
LAST_VALUE(name) OVER (
PARTITION BY dept ORDER BY salary DESC, name
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
) AS lowest_earner
FROM employees;
The full frame makes the last IT name Ivo on all five rows. Reversing the order and using FIRST_VALUE is another way to retrieve the low-end row. Check NULL placement too when missing measures can enter the order.
Count positions from one
NTH_VALUE(name, 2) returns the second name in its frame. With the default frame and the same unique sample order, Eva's frame has only one row, so its result is NULL. Gus is second, and every later growing frame contains him. A full-partition frame returns Gus even on Eva's row. SQL Server has FIRST_VALUE and LAST_VALUE but no NTH_VALUE.
Choose an extreme or a row identity
MAX(salary) OVER (PARTITION BY dept) gives 5100 throughout IT because its unordered window covers the whole partition. It is convenient when only the extreme number matters. Adding an ordered frame can turn it into a running maximum; MAX also uses its frame.
A value function can retrieve a different column from the selected row, such as the highest earner's name. It can also fetch a non-extreme position, such as the second row. These are row positions, so NTH_VALUE(..., 2) does not mean the second distinct salary level.
For chronological comparisons, a first-value baseline can restart each year. Monthly revenue 200, 250, 225 and 270 minus the first revenue of that year gives 0, 50, 25 and 70. Partition by the entity and year when each entity needs its own annual baseline.
Key Takeaways
- Positional value functions read positions in the current frame.
- Use a full-partition frame when every row needs the partition's final value.
NTH_VALUEcounts from 1 and returns NULL when that position is absent.- A tie-breaker is essential when the selected row's identity matters.
- An unordered partitioned
MAXgives an extreme number; a value function can retrieve another column of that row.
4.3 Detect changes, streaks and gaps
An island is a maximal run with no break under the chosen rule. A gap separates two such runs. The rule may mean consecutive calendar dates, unchanged statuses or event timestamps no more than a chosen time apart.
Turn changes into start flags
Compare the current status with LAG(status) within each account. An ordinary <> comparison becomes unknown when either value is NULL. PostgreSQL's IS DISTINCT FROM detects a change to or from NULL. Mark the first row separately, including when its own status is NULL:
CASE WHEN ROW_NUMBER() OVER w = 1
OR status IS DISTINCT FROM LAG(status) OVER w
THEN 1 ELSE 0 END AS starts_run
Here w orders by changed_at, event_id inside PARTITION BY account_id, with event_id unique. In a later query, the cumulative sum of these start flags labels the runs. The later layer is needed because one window result cannot be nested inside another window call.
Group consecutive dates
User 1 logged in on March 1, 2, 3, 5, 6 and 9, 2026. Within consecutive dates, subtracting the row number gives the same date:
| Login date | Row number | Date minus row number |
|---|---|---|
| March 1 | 1 | February 28 |
| March 2 | 2 | February 28 |
| March 3 | 3 | February 28 |
| March 5 | 4 | March 1 |
| March 6 | 5 | March 1 |
| March 9 | 6 | March 3 |
PostgreSQL can use this constant difference as a grouping key:
WITH days AS (
SELECT DISTINCT user_id, login_date FROM logins
), numbered AS (
SELECT user_id, login_date,
login_date - CAST(ROW_NUMBER() OVER (
PARTITION BY user_id ORDER BY login_date
) AS integer) AS island_key
FROM days
)
SELECT user_id, MIN(login_date) AS streak_start,
MAX(login_date) AS streak_end, COUNT(*) AS days
FROM numbered
GROUP BY user_id, island_key
ORDER BY user_id, streak_start;
The streaks last 3, 2 and 1 days. The DISTINCT stage establishes one row per user-day. Without it, repeated logins shift row numbers and break the date pattern. A DENSE_RANK variant can give repeated dates the same offset, but then count distinct dates to measure days. PostgreSQL date subtraction needs an integer here, so cast the row number from its returned bigint.
Allow a time tolerance
For sessions, define a new session after more than 30 minutes of inactivity. Events at 09:00, 09:10, 09:55 and 10:05 have gaps of 10, 45 and 10 minutes. The start flags are 1, 0, 1 and 0; their running sum gives session IDs 1, 1, 2 and 2.
Use one CTE to retrieve the previous timestamp, another to mark starts and another to sum those flags per user. An exactly 30-minute gap stays in the session under this rule. A unique timestamp-and-ID order makes event neighbors repeatable.
To list missing dates, retrieve the next login date with LEAD. A gap exists when it is more than one day later. Its boundaries are the day after the current login and the day before the next one. The sample has missing March 4 and March 7–8. The final login has no next date, so it does not establish a bounded later gap.
Key Takeaways
- Define the continuity rule before identifying islands.
- Use a unique order and explicitly mark the first row of a run.
- Deduplicate to one row per day before subtracting row numbers from dates.
- A cumulative sum of start flags labels successive runs.
- Use separate query stages for predecessor values, flags and their running sum.
LEADsupplies the next observed date for computing bounded gaps.- NULL-aware comparisons detect status changes that ordinary inequality misses.
5Build reliable analytical queries
A useful analytical report often needs several query stages: establish what one row represents, summarize the raw records, compare those summaries and select the rows to report. Percentages and growth rates make those dependencies visible. Build the report one layer at a time, then check it with small totals and boundary cases. Finally, inspect database-specific syntax and the query plan so correctness survives both a new data set and a move to another system.
5.1 Combine windows, aggregates and CTEs into a report
The grain of a report is what one row represents: an order, store, day or month. Choose it before writing the window. A monthly growth calculation needs monthly rows; comparing individual invoices would answer a different question.
Calculate a share at the right grain
Group the sales data to one row per store, then total the grouped values:
SELECT store, SUM(units) AS total,
ROUND(SUM(units) * 100.0
/ NULLIF(SUM(SUM(units)) OVER (), 0), 1) AS pct
FROM daily_sales
GROUP BY store
ORDER BY store;
North sold 76 units and South 50, for 126 overall. Their shares round to 60.3% and 39.7%. The inner sums create store totals; the outer window sum supplies the denominator on both store rows. 100.0 preserves fractional division and NULLIF handles a zero grand total.
For a day's share of its own store, keep the daily grain and partition the denominator: units * 100.0 / NULLIF(SUM(units) OVER (PARTITION BY store), 0). North's March 7 share is about 21.1%; South's March 5 share is 26%. The denominator must cover the population named by the question.
Build a report in stages
Suppose invoices(invoice_date, amount) must return months with more than 15% revenue growth. In PostgreSQL:
WITH monthly AS (
SELECT DATE_TRUNC('month', invoice_date) AS month_start,
SUM(amount) AS revenue
FROM invoices
GROUP BY DATE_TRUNC('month', invoice_date)
), previous AS (
SELECT month_start, revenue,
LAG(revenue) OVER (ORDER BY month_start) AS prev_revenue
FROM monthly
), growth AS (
SELECT month_start, revenue,
(revenue - prev_revenue) * 100.0
/ NULLIF(prev_revenue, 0) AS pct_growth
FROM previous
)
SELECT month_start, revenue, ROUND(pct_growth, 1) AS pct_growth
FROM growth
WHERE pct_growth > 15
ORDER BY month_start;
Monthly revenue of 200, 250, 225 and 270 gives growth NULL, 25, -10 and 20 percent. February and April qualify. January has no previous month, so its growth is NULL and fails the comparison. The report filters the unrounded result and rounds only the displayed value.
Inspect monthly first: each month must occur once. Then inspect previous to verify the matched months, and inspect growth before adding its filter. A missing month makes LAG compare with the previous observed month. If calendar-month growth is required, complete the calendar and decide how a missing revenue should be represented before calculating change.
Combine independent windows
One select list can show a running total, a rank and a difference from an average, each with its own window. These expressions analyze the same available rows without changing one another's results. A dependent calculation belongs in a later layer.
For a second check, compute department averages in a grouped subquery and join them back to employees. Compare those averages with AVG(salary) OVER (PARTITION BY dept) on a small sample. Agreement across two methods can expose a partition or filter mistake that checking only the final formatted report would miss.
Key Takeaways
- Decide the output grain before aggregating or comparing rows.
- Use a window over grouped totals for shares of a grand total.
- Build dependent calculations in inspectable query stages.
- Calculate growth before filtering it and round only for display.
- Independent windows can coexist in one select list.
5.2 Check correctness, portability and performance
A query can look plausible while using the wrong rows. Check its population, order, frame and arithmetic before judging the final formatting. Then examine the features and execution plan of the database that will run it.
Test small invariants and boundaries
Use a sample containing a tie, a one-row group, a NULL measure and a missing date. Check results you can calculate independently:
- The final cumulative sum equals the group's total when both use the same rows.
- The largest row number equals the partition's row count.
- Ranks begin at 1; relative ranks and cumulative distributions lie between 0 and 1.
- Unrounded shares of a nonzero total sum to 100%; rounded displayed shares can differ slightly.
For repeatable row positions, add a unique final sort key to ROW_NUMBER, NTILE, offset functions and row-based frames. Preserve intentional ties in value rankings such as RANK by keeping their window order limited to the ranking values. Stable display order can use extra keys separately.
Check arithmetic types and unknown values
In PostgreSQL, SQL Server and SQLite, integer division truncates: 76 * 100 / 126 gives 60. Use 100.0 or a suitable noninteger cast to retain the fraction. SQLite's CAST(... AS DECIMAL) can retain an integer representation, so use REAL there. MySQL's / already produces a fractional result for these integers.
AVG skips NULL values. A three-row frame containing 8, NULL and 16 averages two known values to 12. Replacing NULL with zero changes the average to 8. Do that only if NULL means zero; otherwise pair the average with COUNT(measure) OVER the same frame to show how many values support it. SQL Server also needs a decimal input cast when averaging integers with fractional results.
Keep dialect assumptions explicit
| Feature | Support relevant to these examples |
|---|---|
GROUPS and EXCLUDE | PostgreSQL and SQLite |
Offset RANGE | PostgreSQL and MySQL; SQLite supports numeric offsets |
Named WINDOW | PostgreSQL, MySQL, SQLite; SQL Server 2022+ at compatibility level 160+ |
NULLS FIRST or NULLS LAST | PostgreSQL and SQLite; not MySQL or SQL Server |
NTH_VALUE | PostgreSQL, MySQL, SQLite and Oracle; not SQL Server |
QUALIFY | Snowflake, BigQuery, DuckDB and Teradata |
The date arithmetic and interval-range examples use PostgreSQL. SQLite offset ranges over dates need a numeric date representation; an ISO date string does not supply PostgreSQL interval behavior.
Window support arrived in PostgreSQL 8.4, MySQL 8.0 and SQLite 3.25. SQL Server introduced ranking and partitioned aggregates in 2005 and added frames and several value functions in 2012. For an older deployment, check the specific function and frame, not just whether any window function works.
Inspect sorts and window work
Window evaluation often needs rows ordered by partition keys and then order keys. An index such as (store, sale_date) can supply a useful order. Several compatible windows can share ordering work; different specifications can need additional sorts.
Use PostgreSQL EXPLAIN to look for sorts and WindowAgg steps. A named window makes shared definitions clear, but does not guarantee one particular plan. Filter early when the removed rows should not contribute. A filter on a calculated row number usually comes after the relevant window work; moving a history cutoff earlier just to reduce rows can make the answer wrong.
Key Takeaways
- Check independent totals, one-row partitions, ties, missing dates and NULL measures.
- Stabilize row-based choices without accidentally removing intended ranking ties.
- Check division and average return types before reporting fractional results.
- Aggregate counts reveal how many known values support an average.
- Confirm the specific dialect features used by the query.
- Inspect the plan for sort and window work; early filters must preserve the intended population.
SQL Window Functions examples
1Add comparisons without losing detail
12 steps
- 1IntroductionKeep the person and add the comparison
An employee report needs each name, salary and department average on the same row. A department summary alone loses the names, while a window calculation keeps them.
Follow the calculation from the available rows to its partition and order. Then decide where a filter belongs so it removes displayed rows without accidentally changing the population used for the comparison.
- 2ExplanationChoose one row per employee
GROUP BY creates one summary row per group. A window function returns its result beside each available row.
For the nine employees, grouping by department gives two averages: Sales 3950 and IT 4700. The window expression
AVG(salary) OVER (PARTITION BY dept)gives those same averages on nine employee rows, leaving names and individual salaries available for comparison. - 3ExampleCalculate Ana's difference
Sales has salaries 4200, 3900, 4200 and 3500. Their total is 15800, giving an average of 3950 across four people.
SELECT name, salary, salary - AVG(salary) OVER (PARTITION BY dept) AS diff FROM employees;Ana's salary of 4200 produces a difference of 250. Dev's 3500 produces -450. Both employees remain in the result; the expression adds their comparisons.
- 4ChallengeChoose the comparison population
An eight-project table has two teams. You need every project ID beside the average duration of all eight projects. What window expression gives the average, and how many rows remain?
---reveal---
Use
AVG(duration) OVER (); all eight project rows remain. The empty definition creates one calculation population across the available rows. Partitioning by team would answer a different question: the average for each project's own team. - 5ExampleRestart the store sequence
North has six recorded dates and South has five. This expression numbers each store independently:
ROW_NUMBER() OVER ( PARTITION BY store ORDER BY sale_date )North receives 1–6 and South receives 1–5. A South row never reads a North predecessor. Removing the partition clause creates one eleven-row sequence, even if the final report displays stores separately.
- 6TipSeparate calculation order from display
A query can calculate in chronological order and display newest dates first. Keep
ORDER BY sale_dateinside the window, then useORDER BY sale_date DESCat the end of the query.The calculation keeps its chronological values. Only their display positions change. A final order also provides a stable presentation; a window order by itself does not promise that the returned rows will appear in that order.
- 7ChallengeKeep a predecessor inside its device
Devices A and B each have several dated readings. A query uses
LAG(reading) OVER (ORDER BY device_id, measured_at). What change stops the first B reading from using A's last reading?---reveal---
Use
LAG(reading) OVER (PARTITION BY device_id ORDER BY measured_at). The partition boundary makes B's first predecessor absent, giving NULL by default. Merely putting device ID first in the order did not create separate sequences. - 8ExampleCalculate the rank before filtering it
A window result is calculated after the same query's
WHERE, so a same-level filter cannot read the rank.WITH ranked AS ( SELECT name, RANK() OVER (ORDER BY salary DESC) AS r FROM employees ) SELECT name FROM ranked WHERE r <= 3;The CTE first gives ranks to all employees. The outer query then keeps Eva and Gus at rank 1 and Femi at rank 3.
- 9ExampleKeep the earlier days available
North's units begin 10, 14 and 9 on March 1, 2 and 3. Its cumulative total on March 3 is 33.
A same-level date filter starting March 3 removes the first two days before the total is calculated, giving 9 instead. To display March 3 onward with full-history totals, compute the totals in a CTE over the full series and apply the date cutoff outside. The date shown can stay the same while the meaning of its total changes.
- 10ChallengeRead a window over grouped totals
After grouping sales by store, a query has totals 28 and 42. What value does
SUM(SUM(units)) OVER ()put beside each store, and why are there two sums?---reveal---
It puts 70 beside both stores. The inner sum creates one total per store from the source rows. The outer window sum reads those two grouped rows and adds their totals. At that stage, the window analyzes store summaries, not raw sale records.
- 11ChallengeSelect employees above their team average
A report must show every employee whose salary exceeds the average of all employees in their department. How would you stage the average and the salary filter?
---reveal---
Calculate
AVG(salary) OVER (PARTITION BY dept) AS dept_avgin a CTE that includes all employees. In the outer query, keepsalary > dept_avg. Filtering salaries first would change the department population and therefore the average used for the decision. - 12RecapCheck the population before the filter
Build the comparison in this order:
- Choose the output grain: a detail row or a grouped summary.
- Set independent partitions and the calculation order.
- Calculate the window result.
- Filter that result in a later query when needed.
Before accepting a plausible number, ask which rows contributed to it. The same expression can give a different answer after an early date or eligibility filter.
2Choose who belongs in a ranked selection
14 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionDecide what a position means
- 2ExplanationNumber rows or rank values
- 3ExampleUse different windows for different meanings
- 4ChallengeFind the second distinct level
- 5ExplanationCompare two population fractions
- 6ExampleSplit rows evenly into buckets
- 7ChallengeInspect a cutoff tie
- 8ExampleChoose the top two per department
- 9Key InsightKeep levels when the rule counts values
- 10TipSelect eligible rows before ranking
- 11ExampleReuse the pattern for duplicate records
- 12ChallengeKeep the latest full record
- 13ChallengePreserve ties and a stable display
- 14RecapName the boundary rule
3Choose exactly which rows a total or average uses
15 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionInspect the frame members
- 2ExampleAccumulate through each order
- 3ExplanationAccumulate through the date instead
- 4ChallengeChoose a row-level running total
- 5ExplanationChoose a unit of frame distance
- 6ExampleCount the preceding peer group
- 7TipRead RANGE in the sort direction
- 8ChallengeCalculate a descending range
- 9ExampleExclude the current employee
- 10ExampleSlide a three-row average
- 11Key InsightCheck completeness with the same frame
- 12ExampleChoose days instead of observations
- 13ChallengeApply a zero-sales policy
- 14ChallengeSeparate row completeness from known data
- 15RecapState the frame and its meaning
4Turn row comparisons into changes and streaks
17 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionFind the right comparison row
- 2ExplanationReach one row back or ahead
- 3ExampleMeasure growth from its earlier baseline
- 4TipCheck which period the offset reaches
- 5ChallengeDistinguish a missing row from a missing value
- 6ExampleCompare with the top salary
- 7ExampleExtend LAST_VALUE to the actual end
- 8ChallengeFetch a future frame position
- 9ExplanationDefine an uninterrupted run
- 10ExampleGive consecutive days a common key
- 11TipEstablish one row per day first
- 12ChallengeFind the streak and its gap
- 13ExampleConvert inactivity into start flags
- 14Key InsightMark a NULL first status explicitly
- 15ChallengePredict session IDs at the threshold
- 16ChallengePlan a per-device session report
- 17RecapChoose the comparison scope
5Build and check a monthly growth report
12 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionBuild one inspectable stage at a time
- 2ExplanationSet the grain before applying LAG
- 3ExampleRetrieve the previous total
- 4ExampleCalculate and filter growth
- 5ChallengeSelect a month by its actual growth
- 6ConnectionUse grouped totals for a different denominator
- 7TipCheck invariants and the boundary rows
- 8ChallengeFind where the fraction was lost
- 9ExplanationCheck the feature before moving the query
- 10TipInspect the work behind the window
- 11ChallengeKeep history while reducing unnecessary work
- 12RecapRead each stage as a result table
SQL Window Functions practice questions
Set 1: Choose the rows, order and ranking rule10 Practice Questions
Question 1 of 10
NTILE(3). What are the bucket sizes from first to third?Show answerHide answer
NTILE gives that extra row to the first bucket, producing sizes 3, 2 and 2. Assigning it to the last bucket would reverse the rule; the sizes stay as even as possible and larger buckets come first.Question 2 of 10
SELECT technician_id, AVG(score) OVER (PARTITION BY team_id) FROM technicians, with no filters or other clauses?Show answerHide answer
GROUP BY result. Partitioning decides which rows contribute to each average; it does not collapse the technicians into team summaries.Question 3 of 10
Show answerHide answer
OVER () would keep detail but combine the hours from all teams into a single comparison population.Question 4 of 10
LAG(reading) restart independently for each device?Show answerHide answer
PARTITION BY device_id gives each device its own predecessor sequence. Merely ordering by device ID puts devices next to each other but leaves them in one partition. The first row of a device could then read the last value of the preceding device.Question 5 of 10
ROW_NUMBER() OVER (ORDER BY measured_at) and ends with ORDER BY device_id, measured_at DESC. In what order are the row numbers assigned?Show answerHide answer
OVER assigns the row numbers, and ascending is its default direction. The final query order only arranges the numbered rows for display. Mentioning device ID in that final order does not create separate device partitions; only PARTITION BY does that.Question 6 of 10
Show answerHide answer
WHERE would remove those rows first and leave a total of 9, even though the displayed date would look correct.Question 7 of 10
Show answerHide answer
Question 8 of 10
Show answerHide answer
Question 9 of 10
Show answerHide answer
Question 10 of 10
Show answerHide answer
ROW_NUMBER gives at most three rows when the outer query keeps positions 1–3. The unique submission ID resolves equal scores repeatably. A dense rank based only on score would keep three score levels and could return more than three submissions.Set 2: Trace cumulative totals and sliding frames10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
SUM from the first row through the current row?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
SUM(amount) OVER (ORDER BY order_date) show on the two July 8 rows?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
ROWS BETWEEN 4 PRECEDING AND CURRENT ROW include at most?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
GROUPS BETWEEN 1 PRECEDING AND CURRENT ROW give on August 7?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
(2, 5), (4, 7), (4, 11), (7, 13). At the row with key 4 and amount 7, what is the sum for RANGE BETWEEN 2 PRECEDING AND CURRENT ROW EXCLUDE TIES?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
AVG(value) and COUNT(value) return?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 3: Compare neighbors, reference rows and activity runs10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
LAST_VALUE(label) OVER (ORDER BY date) return on the second row?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
LAG(value) return on the second row?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
LAG(value, 1, 0) return on November 2?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
(1, 40), (2, 40), (3, 25). What are the second distinct duration, full-frame NTH_VALUE(task_id, 2), and default-frame NTH_VALUE(task_id, 2) on task 1?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
CASE WHEN status IS DISTINCT FROM LAG(status) OVER w THEN 1 ELSE 0 END. What flag does the first row get?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
ROW_NUMBER from each date and counts rows per island. What repair makes both the island and its day count correct?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
LAG and the comparison filter?Show answerHide answer
Save this lesson to see this answer.
Set 4: Design selections and multi-stage reports10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
CUME_DIST for a score of 90?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
CUME_DIST <= 0.4, and how many survive RANK <= 4?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
ROW_NUMBER = 1?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
rn <= 3, then filters active rows. How many rows does it return, and how many should a top-three-active query return?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
35 * 100 / 80 = 43. What change preserves the fractional percentage?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
(device_id, measured_at). What part preserves the report's meaning?Show answerHide answer
Save this lesson to see this answer.
Set 5: Resolve ties, missing periods and query boundaries10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
EXCLUDE GROUP remove from a selected window frame?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
SELECT DISTINCT group_id, COUNT(*) OVER (PARTITION BY group_id) FROM users return?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
SUM(amount) values result?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
LAG(month_start, 2) retrieve?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
COUNT(*) OVER w = 3, but the requirement is three known values. What average does it currently calculate, and what condition repairs completeness?Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
Aggregate function
OVER, it calculates over a window frame.AVG(salary) summarizes a group, while AVG(salary) OVER () keeps the available detail rows.B
Baseline
Bucket
NTILE; its boundary follows position and can divide rows with equal measures.C
Calendar completion
Centered frame
Common table expression
WITH that can provide one stage of a larger analytical query.WHERE.CUME_DIST
Cumulative aggregate
CURRENT ROW
ROWS mode and the current peer-group boundary in RANGE or GROUPS mode.D
Deduplication
DENSE_RANK
Derived table
FROM whose output becomes the input rows and columns available to an enclosing query.Deterministic order
Distribution cutoff
CUME_DIST <= 0.10 filter even when some peers precede it.Duplicate key
E
Execution plan
EXPLAIN can reveal a sort followed by a WindowAgg step for a report.F
FIRST_VALUE
Frame bound
2 PRECEDING starts a three-row trailing frame when its end is CURRENT ROW.Frame exclusion
EXCLUDE CURRENT ROW lets a full-department salary frame average only the employee's colleagues.G
Gap
Grain
GROUP BY
Grouped row
GROUPS frame
I
Incomplete window
Independent windows
Integer division
35 * 100 / 80 gives 43; using 100.0 preserves 43.75.Island
Island key
K
Known-value count
L
LAG
LAG(units) reveals a decline from the previous recorded observation.LAST_VALUE
Latest row per group
LEAD
LEAD(login_date) supplies the next observed day for identifying the gap between logins.Logical query order
WHERE removes observations before a running total is calculated.M
Moving average
N
Named window
WINDOW clause that lets several function calls share partition, order or frame settings.OVER w for both a cumulative sum and a count with the same definition.NTH_VALUE
NTILE
NULL ordering
score DESC NULLS LAST keeps missing scores from appearing above known scores.Null-safe comparison
IS DISTINCT FROM detects a status change from NULL to a known status.NULLIF
NULLIF(prev_revenue, 0) leaves percentage growth undefined after a zero baseline.O
OVER clause
OVER () to COUNT(*) repeats the available row count on each output row.P
Partition
PARTITION BY, within which a window calculation operates independently.Peer rows
ORDER BY, so peer groups depend on the complete sort list.Percent of total
PERCENT_RANK
(rank - 1)/(rows - 1), with 0 for a one-row partition.Percentage change
Q
QUALIFY
WHERE.QUALIFY; PostgreSQL uses an outer query for this pattern.Query stage
R
RANGE frame
RANK
Row offset
ROW_NUMBER
ROWS frame
Running maximum
Running total
S
Session
Sort-compatible index
SQL dialect
RANGE query written for PostgreSQL needs adaptation before it can run in SQL Server.Start flag
T
Tie-breaker
Top N per group
Trailing frame
W
Window frame
Window function
Window order
OVER that determines ranking positions, offsets and ordered frame boundaries.Y
Year-to-date total
About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.