SQL Window Functions and Analytical Queries

Learn to answer analytical questions in SQL without losing the detail rows. Window functions calculate across related rows with 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

  1. Use the OVER clause to calculate across related rows while keeping every row, and place window functions correctly in a query.
    • Compare window functions with GROUP BY aggregates
      See 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 BY
      Split rows into partitions, set the processing order inside each partition, handle NULLs in that order and reuse a window definition with the WINDOW clause.
    • Place window functions correctly in a query
      Use 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.
  2. 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_RANK
      Apply 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_DIST
      Divide 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 duplicates
      Combine a ranking function with an outer filter to keep the best rows per group, decide how ties count and delete duplicate rows.
  3. Build cumulative and rolling calculations, and control exactly which rows each calculation uses with a frame clause.
    • Build running totals and other cumulative values
      Calculate 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 GROUPS
      Write frame clauses that choose exactly which rows around the current row a calculation uses, and know the default frame and its effects.
    • Calculate moving averages
      Smooth a series with row-based and time-based rolling windows, and deal with the first rows, missing dates and integer averages.
  4. 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 LEAD
      Fetch values from earlier and later rows to calculate differences, growth rates and time between events.
    • Pick the first, last or nth value of a window
      Use FIRST_VALUE, LAST_VALUE and NTH_VALUE to compare each row with a reference row, and set the frame so they return what you expect.
    • Detect changes, streaks and gaps
      Flag rows where a value changes, group consecutive rows into streaks (gaps and islands) and measure each streak and gap.
  5. 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 report
      Answer 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 performance
      Make window queries repeatable and correct, know the main differences between database systems and keep the queries efficient.

SQL Window Functions study guide

5 chapters

1

Explain 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):

DepartmentEmployees and salaries
SalesAna 4200; Ben 3900; Chen 4200; Dev 3500
ITEva 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
FamilyExamplesRole of OVER
Ordinary aggregatesSUM, AVG, COUNT, MIN, MAXTurns the aggregate into a window calculation
Dedicated window functionsROW_NUMBER, RANK, LAG, FIRST_VALUERequired 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 dept gives 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:

StoreDay and units
North01: 10; 02: 14; 03: 9; 04: 15; 06: 12; 07: 16
South01: 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 BY sets 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 BY and HAVING.
  • 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.
  • DISTINCT can reduce rows after window values have been calculated.
2

Rank 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:

NameSalaryROW_NUMBERRANKDENSE_RANK
Eva5100111
Gus5100211
Femi4800332
Hana4500443
Ivo4000554

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
QuestionFunctionWhat the position counts
Which single row is first?ROW_NUMBERIndividual rows
Who is joint first, then third?RANKCompetition places
Who has the second-highest distinct salary?DENSE_RANKSalary 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_NUMBER numbers rows; RANK leaves gaps after ties; DENSE_RANK counts 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:

NameRANKPERCENT_RANKCUME_DIST
Eva100.4
Gus100.4
Femi30.50.6
Hana40.750.8
Ivo511

PERCENT_RANK() uses the competition rank:

percent rank=rank−1partition rows−1

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

  • NTILE balances row counts and can split equal values.
  • PERCENT_RANK is (rank - 1) / (row count - 1), with 0 for one row.
  • CUME_DIST includes 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 ruleWindow orderEffect of a salary tie
ROW_NUMBER <= 2Salary descending, then unique IDKeeps at most two rows
RANK <= 2Salary descendingKeeps all rows at competition places 1 or 2
DENSE_RANK <= 2Salary descendingKeeps 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.
3

Compute 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 IDDate in March 2026Amount
10150
20130
30220
40340

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 ROWS frame and unique order give a repeatable total through each individual row.
  • The default ordered frame includes the current peer group.
  • Period expressions in PARTITION BY control 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
ModeWhat the distance countsExample ending at CURRENT ROW
ROWSIndividual ordered rows2 PRECEDING includes at most three rows
RANGEDistance in the sort value2 PRECEDING in ascending numeric order includes values from current minus 2 through current
GROUPSPeer groups1 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:

  1. UNBOUNDED PRECEDING
  2. An offset PRECEDING
  3. CURRENT ROW
  4. An offset FOLLOWING
  5. 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 dateResults in order
Default ordered frame80; 80; 100; 140
Cumulative ROWS, adding order ID to the order50; 80; 100; 140
GROUPS BETWEEN 1 PRECEDING AND CURRENT ROW80; 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

  • ROWS counts rows, RANGE measures sort-value distance, and GROUPS counts 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 TIES keeps the current row; EXCLUDE GROUP removes it with its peers.
  • Ranking and offset functions do not use the frame.
  • Check dialect support before using offset RANGE, GROUPS or 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.
  • ROWS follows observations; an interval RANGE follows 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.
4

Compare 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

  • LAG looks back and LEAD looks 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_VALUE counts 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 MAX gives 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 dateRow numberDate minus row number
March 11February 28
March 22February 28
March 33February 28
March 54March 1
March 65March 1
March 96March 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.
  • LEAD supplies the next observed date for computing bounded gaps.
  • NULL-aware comparisons detect status changes that ordinary inequality misses.
5

Build 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
FeatureSupport relevant to these examples
GROUPS and EXCLUDEPostgreSQL and SQLite
Offset RANGEPostgreSQL and MySQL; SQLite supports numeric offsets
Named WINDOWPostgreSQL, MySQL, SQLite; SQL Server 2022+ at compatibility level 160+
NULLS FIRST or NULLS LASTPostgreSQL and SQLite; not MySQL or SQL Server
NTH_VALUEPostgreSQL, MySQL, SQLite and Oracle; not SQL Server
QUALIFYSnowflake, 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

5 Walkthroughs

1

Add comparisons without losing detail

12 steps
Build a department comparison, define independent store sequences and place a filter after a window result.
  1. 1
    IntroductionKeep 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.

  2. 2
    ExplanationChoose 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.

  3. 3
    ExampleCalculate 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.

  4. 4
    ChallengeChoose 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.

  5. 5
    ExampleRestart 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.

  6. 6
    TipSeparate calculation order from display

    A query can calculate in chronological order and display newest dates first. Keep ORDER BY sale_date inside the window, then use ORDER BY sale_date DESC at 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.

  7. 7
    ChallengeKeep 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.

  8. 8
    ExampleCalculate 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.

  9. 9
    ExampleKeep 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.

  10. 10
    ChallengeRead 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.

  11. 11
    ChallengeSelect 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_avg in a CTE that includes all employees. In the outer query, keep salary > dept_avg. Filtering salaries first would change the department population and therefore the average used for the decision.

  12. 12
    RecapCheck the population before the filter

    Build the comparison in this order:

    1. Choose the output grain: a detail row or a grouped summary.
    2. Set independent partitions and the calculation order.
    3. Calculate the window result.
    4. 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.

2

Choose who belongs in a ranked selection

14 steps
Trace salary ties, compare relative positions and select complete records within groups.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionDecide what a position means
  2. 2
    ExplanationNumber rows or rank values
  3. 3
    ExampleUse different windows for different meanings
  4. 4
    ChallengeFind the second distinct level
  5. 5
    ExplanationCompare two population fractions
  6. 6
    ExampleSplit rows evenly into buckets
  7. 7
    ChallengeInspect a cutoff tie
  8. 8
    ExampleChoose the top two per department
  9. 9
    Key InsightKeep levels when the rule counts values
  10. 10
    TipSelect eligible rows before ranking
  11. 11
    ExampleReuse the pattern for duplicate records
  12. 12
    ChallengeKeep the latest full record
  13. 13
    ChallengePreserve ties and a stable display
  14. 14
    RecapName the boundary rule
3

Choose exactly which rows a total or average uses

15 steps
Trace peer-inclusive totals, compare frame modes and handle incomplete or missing-day averages.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionInspect the frame members
  2. 2
    ExampleAccumulate through each order
  3. 3
    ExplanationAccumulate through the date instead
  4. 4
    ChallengeChoose a row-level running total
  5. 5
    ExplanationChoose a unit of frame distance
  6. 6
    ExampleCount the preceding peer group
  7. 7
    TipRead RANGE in the sort direction
  8. 8
    ChallengeCalculate a descending range
  9. 9
    ExampleExclude the current employee
  10. 10
    ExampleSlide a three-row average
  11. 11
    Key InsightCheck completeness with the same frame
  12. 12
    ExampleChoose days instead of observations
  13. 13
    ChallengeApply a zero-sales policy
  14. 14
    ChallengeSeparate row completeness from known data
  15. 15
    RecapState the frame and its meaning
4

Turn row comparisons into changes and streaks

17 steps
Retrieve neighbors and reference values, then label consecutive-day streaks and inactivity sessions.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionFind the right comparison row
  2. 2
    ExplanationReach one row back or ahead
  3. 3
    ExampleMeasure growth from its earlier baseline
  4. 4
    TipCheck which period the offset reaches
  5. 5
    ChallengeDistinguish a missing row from a missing value
  6. 6
    ExampleCompare with the top salary
  7. 7
    ExampleExtend LAST_VALUE to the actual end
  8. 8
    ChallengeFetch a future frame position
  9. 9
    ExplanationDefine an uninterrupted run
  10. 10
    ExampleGive consecutive days a common key
  11. 11
    TipEstablish one row per day first
  12. 12
    ChallengeFind the streak and its gap
  13. 13
    ExampleConvert inactivity into start flags
  14. 14
    Key InsightMark a NULL first status explicitly
  15. 15
    ChallengePredict session IDs at the threshold
  16. 16
    ChallengePlan a per-device session report
  17. 17
    RecapChoose the comparison scope
5

Build and check a monthly growth report

12 steps
Aggregate to monthly rows, calculate growth, apply a threshold and check correctness and portability.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionBuild one inspectable stage at a time
  2. 2
    ExplanationSet the grain before applying LAG
  3. 3
    ExampleRetrieve the previous total
  4. 4
    ExampleCalculate and filter growth
  5. 5
    ChallengeSelect a month by its actual growth
  6. 6
    ConnectionUse grouped totals for a different denominator
  7. 7
    TipCheck invariants and the boundary rows
  8. 8
    ChallengeFind where the fraction was lost
  9. 9
    ExplanationCheck the feature before moving the query
  10. 10
    TipInspect the work behind the window
  11. 11
    ChallengeKeep history while reducing unnecessary work
  12. 12
    RecapRead each stage as a result table

SQL Window Functions practice questions

50 Practice Questions in 5 sets

Set 1: Choose the rows, order and ranking rule10 Practice Questions

Question 1 of 10

Seven ordered rows are divided with NTILE(3). What are the bucket sizes from first to third?
  1. 3, 2 and 2 rows
  2. 2, 2 and 3 rows
  3. 3, 3 and 1 rows
  4. 2, 3 and 2 rows
Show answerHide answer
Answer: A
Seven rows divide into two per bucket with one row left over. 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

A table has 12 technicians in three teams. What is the output row count of SELECT technician_id, AVG(score) OVER (PARTITION BY team_id) FROM technicians, with no filters or other clauses?
  1. 3 rows
  2. 12 rows
  3. 1 row
  4. 36 rows
Show answerHide answer
Answer: B
The window average adds a team value to each technician row, so all 12 rows remain. Three rows would be the shape of a team-level GROUP BY result. Partitioning decides which rows contribute to each average; it does not collapse the technicians into team summaries.

Question 3 of 10

A studio needs every project ID beside its team's total hours. What query shape supplies both at that detail level?
  1. Group by team ID and select SUM(hours) for each team.
  2. Group by project ID and select SUM(hours) for each project.
  3. Select project IDs with SUM(hours) OVER () for all teams.
  4. Select project IDs with SUM(hours) OVER (PARTITION BY team_id).
Show answerHide answer
Answer: D
The partitioned sum keeps one row per project while using all projects from its team in the total. Grouping only by project ID produces project totals, not team totals. An empty OVER () would keep detail but combine the hours from all teams into a single comparison population.

Question 4 of 10

What clause makes LAG(reading) restart independently for each device?
  1. PARTITION BY device_id
  2. ORDER BY device_id
  3. GROUP BY device_id
  4. ORDER BY reading
Show answerHide answer
Answer: A
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

A query uses 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?
  1. Within each device by measured_at descending.
  2. Across all rows by device_id, then time descending.
  3. Across all rows by measured_at ascending.
  4. Within each device by measured_at ascending.
Show answerHide answer
Answer: C
The order inside 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

An account has charges 7, 5 and 9 on May 1, 2 and 3. A report must display May 3 with its cumulative total of 21. Where should its May 3 date filter go?
  1. In WHERE before computing the cumulative total.
  2. In HAVING beside the cumulative window expression.
  3. In an outer query after computing the cumulative total.
  4. In the window order before the charge amount.
Show answerHide answer
Answer: C
The window needs May 1 and 2 to contribute 12 before May 3 adds 9. An outer date filter hides earlier rows after their contribution is calculated. A same-level WHERE would remove those rows first and leave a total of 9, even though the displayed date would look correct.

Question 7 of 10

A query must return one row per branch, its total visits and its share of visits across all branches. The source has several rows per branch. What pair of expressions gives the numerator and denominator in a query grouped by branch?
  1. SUM(visits) and SUM(SUM(visits)) OVER ()
  2. visits and SUM(visits) OVER ()
  3. SUM(visits) and COUNT(*) OVER ()
  4. SUM(visits) and SUM(SUM(visits)) OVER (PARTITION BY branch)
Show answerHide answer
Answer: A
Grouping first creates branch totals, which become the input rows for the window sum. The denominator must add those branch totals across the full grouped result. Partitioning the denominator by branch would leave each branch alone and make every nonzero branch appear to have a 100% share.

Question 8 of 10

Scores ordered descending are 96, 88, 88 and 70. What are the competition rank and dense rank of 70?
  1. Competition rank 3; dense rank 3.
  2. Competition rank 4; dense rank 4.
  3. Competition rank 3; dense rank 4.
  4. Competition rank 4; dense rank 3.
Show answerHide answer
Answer: D
Three rows precede 70, so its competition rank is 4. Only two distinct score levels precede it, so its dense rank is 3. Giving competition rank 3 overlooks the extra place occupied by the tied 88s; competition ranks count preceding rows, not just distinct scores.

Question 9 of 10

A report must preserve equal score ranks but display tied contestants by their unique ID. Where should contestant ID appear?
  1. In the ranking window order after the score column.
  2. In the final query order, outside the score-ranking window.
  3. In PARTITION BY together with the score column.
  4. In a frame clause after the score-ranking window.
Show answerHide answer
Answer: B
The ranking window should order by score alone so equal scores remain peers. The final query order can then arrange those peers by ID without changing their rank. Adding the unique ID inside the ranking window separates the peers and turns the intended tie into distinct places.

Question 10 of 10

A school needs at most three highest-scoring submissions per class, resolving equal scores by unique submission ID. What ranking and filter fit?
  1. Partitioned DENSE_RANK, then an outer rank <= 3 filter.
  2. Global ROW_NUMBER, then an outer rn <= 3 filter.
  3. Partitioned ROW_NUMBER, then an outer rn <= 3 filter.
  4. Global descending score order, then a final LIMIT 3.
Show answerHide answer
Answer: C
A class partition restarts numbering, and 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

Ordered amounts are 6, 13 and 4. What is the last result of a cumulative SUM from the first row through the current row?
  1. 17
  2. 4
  3. 23
  4. 19
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

Two orders on July 8 have amounts 18 and 12; one order on July 9 has amount 5. What totals does SUM(amount) OVER (ORDER BY order_date) show on the two July 8 rows?
  1. 30 on both rows
  2. 18 then 30
  3. 18 on both rows
  4. 30 then 35
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A cumulative sum must restart each month for each warehouse, including data from several years. What partition keys fit?
  1. Warehouse and month number
  2. Year and month, without warehouse
  3. Warehouse and calendar year
  4. Warehouse, year and month
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

How many rows can ROWS BETWEEN 4 PRECEDING AND CURRENT ROW include at most?
  1. 4 rows
  2. 5 rows
  3. 6 rows
  4. 9 rows
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

Peer groups ordered by day have totals 11 on August 2, 17 on August 4 and 8 on August 7. What sum does GROUPS BETWEEN 1 PRECEDING AND CURRENT ROW give on August 7?
  1. 8
  2. 36
  3. 19
  4. 25
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

In PostgreSQL, ascending sort keys and amounts are (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?
  1. 23
  2. 18
  3. 12
  4. 5
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

Recorded quantities are 9 on September 1, 15 on September 2 and 21 on September 5. What is the trailing three-row average on September 5?
  1. 15
  2. 21
  3. 18
  4. 9
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A three-row frame contains values 6, NULL and 18. What pair do AVG(value) and COUNT(value) return?
  1. 12 and 2
  2. 8 and 3
  3. 12 and 3
  4. 8 and 2
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

In PostgreSQL, a device records 8 on October 1, 20 on October 2, 14 on October 5 and 26 on October 6. At October 5, how do a trailing three-row average and a trailing three-calendar-day average over recorded rows compare?
  1. The row average is 14; the calendar average is 17.
  2. The row average is 14; the calendar average is 14.
  3. The row average is 17; the calendar average is 14.
  4. The row average is 14; the calendar average is about 4.67.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

In SQL Server, a window average of integer values 3 and 8 must retain the fraction. What expression supplies it?
  1. CAST(AVG(value) OVER () AS decimal(10,2))
  2. AVG(value) OVER () * 1.0
  3. AVG(CAST(value AS decimal(10,2))) OVER ()
  4. AVG(COALESCE(value, 0)) OVER ()
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

Rows ordered by a unique date have labels "oak", "pine" and "elm". What does LAST_VALUE(label) OVER (ORDER BY date) return on the second row?
  1. "pine"
  2. "oak"
  3. "elm"
  4. NULL
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

Values in unique time order are 11, 7 and 16. What does LAG(value) return on the second row?
  1. 7
  2. 16
  3. NULL
  4. 11
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A sensor has values NULL on November 1 and 9 on November 2. What does LAG(value, 1, 0) return on November 2?
  1. 0
  2. NULL
  3. 9
  4. 1
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

Monthly totals are 80, 100 and 90. What is the third month's percentage change from its predecessor?
  1. -12.5%
  2. 10%
  3. -10%
  4. About -11.1%
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

In PostgreSQL, tasks ordered by duration descending, then unique task ID, are (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?
  1. Duration 40; full-frame ID 2; default-frame NULL.
  2. Duration 25; full-frame ID 2; default-frame NULL.
  3. Duration 25; full-frame ID 3; default-frame NULL.
  4. Duration 25; full-frame ID 2; default-frame ID 2.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

One user has distinct login dates December 2, 3, 6, 7 and 8. What are the consecutive-day streak lengths in chronological order?
  1. 3 and 2 days
  2. 2 and 4 days
  3. 1 and 3 days
  4. 2 and 3 days
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

In PostgreSQL, a status history begins with NULL. Its start flag is CASE WHEN status IS DISTINCT FROM LAG(status) OVER w THEN 1 ELSE 0 END. What flag does the first row get?
  1. 0
  2. 1
  3. NULL
  4. An error
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A user has events at 08:00, 08:25, 08:55 and 09:26. A new session starts after more than 30 minutes of inactivity. What session IDs result from start flags and their cumulative sum?
  1. 1, 1, 2 and 3
  2. 1, 2, 3 and 4
  3. 1, 1, 1 and 2
  4. 1, 1, 2 and 2
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

In PostgreSQL, one user logs in twice on January 10 and once on January 11. A daily-streak query subtracts ROW_NUMBER from each date and counts rows per island. What repair makes both the island and its day count correct?
  1. Keep all records but change only the final count to distinct dates.
  2. Keep all records but order row numbers by date and event ID.
  3. Keep all records but replace NULL values with zero.
  4. Deduplicate user-date rows before numbering and counting.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A report must keep readings below the previous reading from each device. How should it use LAG and the comparison filter?
  1. Put LAG per device directly in the same query's WHERE.
  2. Compute LAG per device in a CTE, then compare in the outer WHERE.
  3. Filter low readings first, then compute LAG on those remaining.
  4. Use HAVING to compare the reading with a same-level LAG.
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

A ranking window orders non-NULL response times ascending. What response time receives rank 1?
  1. The smallest response time
  2. The largest response time
  3. The middle response time
  4. The most frequent response time
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

Five scores ordered descending are 90, 90, 75, 60 and 45. What is CUME_DIST for a score of 90?
  1. 0
  2. 0.2
  3. 0.4
  4. 0.5
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

Ten customers have descending spending values 100, 95, 90, 80, 80, 70, 60, 50, 40 and 30. How many rows survive CUME_DIST <= 0.4, and how many survive RANK <= 4?
  1. 4 rows and 4 rows
  2. 3 rows and 5 rows
  3. 5 rows and 5 rows
  4. 3 rows and 3 rows
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A customer has orders ID 21 and ID 24 on the same latest date. The chosen policy is to keep the higher ID. What window order selects the intended latest complete row with ROW_NUMBER = 1?
  1. ORDER BY order_date DESC, order_id ASC
  2. ORDER BY order_id ASC, order_date DESC
  3. ORDER BY order_date ASC, order_id DESC
  4. ORDER BY order_date DESC, order_id DESC
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A team has scores 99 inactive, 92 active, 85 inactive, 81 active and 76 active. A query numbers all rows by score descending, keeps rn <= 3, then filters active rows. How many rows does it return, and how many should a top-three-active query return?
  1. It returns 1 row; it should return 3.
  2. It returns 2 rows; it should return 3.
  3. It returns 3 rows; it should return 3.
  4. It returns 1 row; it should return 1.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A report has one grouped row per region with totals 45, 30 and 25. What denominator is needed for the first region's percentage share of all regions?
  1. 45
  2. 3
  3. 55
  4. 100
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

Invoices occur many times per month. A report needs months whose revenue grew more than 12% over the previous observed month. What sequence of operations gives that report?
  1. Retrieve prior invoice amount, compute growth, group by month, then filter.
  2. Filter invoices by 12% growth, group by month, then retrieve prior revenue.
  3. Group by month, retrieve prior monthly revenue, compute growth, then filter.
  4. Group by month, filter high-revenue months, then compute their adjacent growth.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

Unrounded percentage growth is 12.04%, and display rounding gives 12.0%. The report requires growth strictly greater than 12%. Should the month appear?
  1. No; filter the displayed 12.0% result.
  2. Yes; filter the unrounded 12.04% result.
  3. Yes; replace the test with greater than or equal to 12%.
  4. No; compare the current total directly with 12.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

In PostgreSQL, integer values satisfy 35 * 100 / 80 = 43. What change preserves the fractional percentage?
  1. Use ROUND(35 * 100 / 80, 1).
  2. Use 35 * 100.0 / 80.
  3. Use (35 / 80) * 100.
  4. Use CAST(35 * 100 / 80 AS integer).
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A PostgreSQL report calculates full-history per-device cumulative totals, then shows only the last week. A proposed optimization moves the date cutoff into the window query and adds an index on (device_id, measured_at). What part preserves the report's meaning?
  1. Keep the cutoff outside; the index can still support the window order.
  2. Move the cutoff inside; the index restores the missing history.
  3. Move the cutoff inside; partitioning restores the earlier totals.
  4. Keep the cutoff outside; remove the index to preserve row order.
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

What does EXCLUDE GROUP remove from a selected window frame?
  1. Only the current row itself
  2. Other peers, keeping the current row
  3. The current row and all its peers
  4. The preceding peer group only
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A table has six users in group X and four in group Y. What rows does SELECT DISTINCT group_id, COUNT(*) OVER (PARTITION BY group_id) FROM users return?
  1. X with 1 and Y with 1
  2. Ten rows, each with a count of 1
  3. One row with a count of 10
  4. X with 6 and Y with 4
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A category has item scores 120, 120, 95, 95 and 70. The requirement is to retain every item at the top two distinct scores and display ties by unique item ID. What ranking rule fits?
  1. Dense rank by score and ID, filter at 2, then display by ID.
  2. Dense rank by score alone, filter at 2, then display by score and ID.
  3. Competition rank by score alone, filter at 2, then display by ID.
  4. Row number by score and ID, filter at 2, then display by score.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A unique ordered sequence has amounts NULL, NULL, 7 and NULL. What cumulative SUM(amount) values result?
  1. NULL, NULL, 7 and 7
  2. 0, 0, 7 and 7
  3. NULL, NULL, 7 and NULL
  4. NULL, NULL, 7 and 0
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A daily series records 12 on February 1, 18 on February 2 and 30 on February 5. A report requires the February 3–5 mean with absent days treated as zero. What is the mean, and what preparation is needed?
  1. 30; use an interval range over the existing rows.
  2. 20; use the last three recorded rows in a row frame.
  3. 16; average all five days after creating missing dates.
  4. 10; create the missing dates and give them zero values.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A monthly table contains January, February, April and May, exactly once each. At May, which month does LAG(month_start, 2) retrieve?
  1. March
  2. February
  3. April
  4. January
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A user has distinct login dates March 10, 11, 14 and 15. In PostgreSQL, subtract each date's chronological row number from the date. How many island keys result, and what bounded missing-date interval lies between them?
  1. Two keys; March 12–13 is missing.
  2. One key; March 12–13 is missing.
  3. Two keys; March 11–14 is missing.
  4. Three keys; March 12–14 is missing.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

In PostgreSQL, an account's statuses in unique time order are NULL, NULL, 'open', 'open', NULL. The first row starts a run, and every status change, including to or from NULL, starts another. What run IDs and change comparison fit?
  1. 1, 1, 1, 1, 1; compare with <>.
  2. 1, 2, 3, 3, 4; compare with IS DISTINCT FROM.
  3. 1, 1, 2, 2, 3; compare with IS DISTINCT FROM.
  4. 0, 0, 1, 1, 2; compare with IS DISTINCT FROM.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A device records quantities 10 and 30 in January and 50 in February. A report needs February's percentage change in monthly total. What growth should appear, and at what stage must the predecessor be retrieved?
  1. About 66.7%; retrieve the predecessor before grouping by month.
  2. 150%; retrieve the predecessor after averaging each month.
  3. 25%; retrieve the predecessor after grouping by month.
  4. 25%; retrieve the predecessor before grouping by month.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A report shows three-row averages over measurements 4, NULL and 14. It labels the frame complete because COUNT(*) OVER w = 3, but the requirement is three known values. What average does it currently calculate, and what condition repairs completeness?
  1. 6; require COUNT(measurement) OVER w = 3.
  2. 9; require COUNT(measurement) OVER w = 3.
  3. 9; require ROW_NUMBER() OVER w = 3.
  4. 6; require COUNT(*) OVER w = 3.
Show answerHide answer

Save this lesson to see this answer.

Stuck on your own question? Homework Help

Key Terms

68 Key Terms, each with its definition

A

Aggregate function
An aggregate function combines values into a result, such as a sum or average; with OVER, it calculates over a window frame.
AVG(salary) summarizes a group, while AVG(salary) OVER () keeps the available detail rows.

B

Baseline
A baseline is the reference value against which another value is compared, such as a series' first observation or its preceding observation.
Subtracting the first revenue from each later revenue measures change since the series began.
Bucket
A bucket is a numbered group of row positions created by NTILE; its boundary follows position and can divide rows with equal measures.
A spending tie can straddle two buckets even though the customers spent equal amounts.

C

Calendar completion
Calendar completion adds missing date rows so calculations can distinguish a complete date series from a sequence of recorded observations.
Fill a missing date with zero only when the data's meaning establishes that no activity occurred.
Centered frame
A centered frame reaches both before and after the current position, so a full result needs following observations as well as earlier ones.
A centered three-row average combines the previous, current and next recorded measurements.
Common table expression
A common table expression is a named query result introduced with WITH that can provide one stage of a larger analytical query.
A ranking CTE exposes a rank column that the outer query can filter with WHERE.
CUME_DIST
CUME_DIST gives the fraction of partition rows ordered ahead of or tied with the current row, including the entire current peer group.
Two tied leaders among five rows each receive cumulative distribution 0.4 in descending order.
Cumulative aggregate
A cumulative aggregate summarizes a growing frame from the group's beginning, using a function such as sum, count, maximum or average.
A cumulative maximum records the largest daily quantity seen so far, even when later quantities fall.
CURRENT ROW
CURRENT ROW names the current row in ROWS mode and the current peer-group boundary in RANGE or GROUPS mode.
When two orders share a date, the default range frame includes both of them even when processing the first one.

D

Deduplication
Deduplication identifies records sharing a chosen duplicate key and retains the preferred record according to an explicit selection rule.
Partition customer records by email and retain the newest row, resolving timestamp ties by ID.
DENSE_RANK
DENSE_RANK assigns peers the same place without gaps, numbering the distinct combinations of window sort values encountered in order.
A dense rank of 2 identifies the second salary level when the window orders only by salary.
Derived table
A derived table is a query used in FROM whose output becomes the input rows and columns available to an enclosing query.
An inner query can calculate row numbers that the enclosing query uses to keep one record.
Deterministic order
A deterministic order assigns an unambiguous position to every row, usually by ending the sort list with a unique key.
Time plus event ID makes a device's previous event repeatable when timestamps tie.
Distribution cutoff
A distribution cutoff selects rows by a relative position boundary whose tie behavior depends on the distribution function used.
A peer group crossing 10% can fail a CUME_DIST <= 0.10 filter even when some peers precede it.
Duplicate key
A duplicate key is the column or column combination defining which records represent duplicates for the particular cleaning task.
Email can define a duplicate partition even though each customer record has its own unique ID.

E

Execution plan
An execution plan describes how the database intends to process a query, including scans, sorts and window evaluation steps.
PostgreSQL EXPLAIN can reveal a sort followed by a WindowAgg step for a report.

F

FIRST_VALUE
FIRST_VALUE returns the expression from the first row of the current frame, providing a reference that depends on its order and boundaries.
The first revenue of a year can serve as the baseline for later revenue differences.
Frame bound
A frame bound identifies the beginning or end of a frame using an unbounded endpoint, the current position or a relative offset.
2 PRECEDING starts a three-row trailing frame when its end is CURRENT ROW.
Frame exclusion
Frame exclusion removes specified current rows or peers from an already selected frame, changing which values reach the function.
EXCLUDE CURRENT ROW lets a full-department salary frame average only the employee's colleagues.

G

Gap
A gap is a missing interval between observed runs whose boundaries exclude the observed values on either side.
Between logins on March 3 and March 7, the missing dates run from March 4 through March 6.
Grain
A report's grain is the meaning of one output row, defining the level at which measures must be grouped before comparison.
A monthly growth report needs one revenue total per month before retrieving the previous total.
GROUP BY
The GROUP BY clause combines source rows with matching grouping values into one result row per group for summary calculations.
Grouping employees by department produces department averages without individual employee names.
Grouped row
A grouped row represents one group produced by aggregation and supplies grouped columns and aggregate values to later window calculations.
After grouping by store, a window can rank the store totals instead of individual sales.
GROUPS frame
A GROUPS frame places boundaries by peer-group positions, treating all rows with equal window sort values as a group.
One preceding date group can contain several orders before the current date group.

I

Incomplete window
An incomplete window contains fewer observations than the intended full span, commonly near the beginning or end of a partition.
The first row of a trailing three-row series has only one observation available for its average.
Independent windows
Independent windows are separate window calculations in one query that use available input columns without depending on one another's results.
One select list can show a salary rank and a department average with different window definitions.
Integer division
Integer division discards a fractional remainder when the database divides integer values using integer arithmetic.
In PostgreSQL, 35 * 100 / 80 gives 43; using 100.0 preserves 43.75.
Island
An island is a maximal uninterrupted run in an ordered sequence under a stated continuity rule, such as consecutive login days.
Login dates on March 1, 2 and 3 form one island when continuity means consecutive calendar dates.
Island key
An island key is a shared value identifying rows in one uninterrupted run, derived from a continuity rule and a suitable ordering method.
Subtracting row numbers from distinct consecutive dates produces a constant date within each run.

K

Known-value count
A known-value count counts non-NULL measures in a frame, showing how many values actually contribute to a NULL-skipping aggregate.
A three-row frame with one NULL has two known values, so its average uses a denominator of two.

L

LAG
LAG retrieves an expression from an earlier row position within the partition's window order, using an optional offset and missing-row default.
Comparing units with LAG(units) reveals a decline from the previous recorded observation.
LAST_VALUE
LAST_VALUE returns the expression from the last row of the current frame, which may end before the partition's final row.
A full frame is needed to show the final observation on every row of a chronological series.
Latest row per group
A latest row per group selection retrieves a whole record at each group's most recent position, with a tie rule for equal timestamps.
A customer partition ordered by date and order ID descending can select the latest complete order.
LEAD
LEAD retrieves an expression from a later row position within the partition's window order, using an optional offset and missing-row default.
LEAD(login_date) supplies the next observed day for identifying the gap between logins.
Logical query order
The logical query order describes the stages that determine a query's meaning, with window calculations following row filtering and grouping.
A date condition in WHERE removes observations before a running total is calculated.

M

Moving average
A moving average averages observations inside a bounded frame that slides through an ordered series, dropping older observations as it advances.
A trailing three-row average smooths daily quantities using each row and its two predecessors.

N

Named window
A named window is a reusable definition in a WINDOW clause that lets several function calls share partition, order or frame settings.
A report can use OVER w for both a cumulative sum and a count with the same definition.
NTH_VALUE
NTH_VALUE returns an expression from a specified frame position counted from 1, or NULL when that position is absent.
The second frame row can still be missing on the first row when the default frame is used.
NTILE
NTILE divides ordered partition rows into a requested number of buckets with sizes differing by at most one, giving extra rows to earlier buckets.
Ten rows divided into four buckets receive bucket sizes 3, 3, 2 and 2 in order.
NULL ordering
NULL ordering is where missing sort values appear relative to known values, as determined by the database or an explicit ordering rule.
In PostgreSQL, score DESC NULLS LAST keeps missing scores from appearing above known scores.
Null-safe comparison
A null-safe comparison treats missing values as comparable for detecting differences, including transitions between NULL and a known value.
PostgreSQL IS DISTINCT FROM detects a status change from NULL to a known status.
NULLIF
NULLIF returns NULL when its two arguments are equal and otherwise returns its first argument, allowing a zero denominator to become NULL.
Using NULLIF(prev_revenue, 0) leaves percentage growth undefined after a zero baseline.

O

OVER clause
An OVER clause specifies the window for a function call, with optional partition, order and frame clauses controlling the calculation.
Adding OVER () to COUNT(*) repeats the available row count on each output row.

P

Partition
A partition is a set of rows sharing the values listed in PARTITION BY, within which a window calculation operates independently.
Partitioning sales by store stops one store's first day from reading another store's last day.
Peer rows
Peer rows are rows with equal values for every expression in the window's ORDER BY, so peer groups depend on the complete sort list.
Equal salaries are peers under salary order but separate when a unique employee ID is added.
Percent of total
A percent of total divides a measure by the sum for its intended population and multiplies by 100, requiring a nonzero denominator.
A store with 30 of the combined 120 units sold contributes 25% of the overall total.
PERCENT_RANK
PERCENT_RANK expresses competition rank relative to partition size using (rank - 1)/(rows - 1), with 0 for a one-row partition.
A row at rank 3 among five rows has a percent rank of 0.5, regardless of its measure's size.
Percentage change
A percentage change expresses the difference from an earlier value as a percentage of that earlier value, requiring a nonzero baseline.
A rise from 80 to 100 is 25% growth because the increase of 20 is compared with 80.

Q

QUALIFY
A QUALIFY clause filters rows using window results in databases that support it, providing a later filter than the same-level WHERE.
Snowflake supports rank filtering with QUALIFY; PostgreSQL uses an outer query for this pattern.
Query stage
A query stage is one layer of a multi-step calculation whose output supplies rows or derived columns to the following layer.
Separate CTEs can produce monthly totals, predecessor values and growth before a final filter.

R

RANGE frame
A RANGE frame chooses boundaries from ordered values, including peers; an offset bounds distance in a single suitable sort expression.
A PostgreSQL date interval can include all recorded observations in the preceding two days.
RANK
RANK assigns peers the same competition place and leaves gaps afterward because the next place counts all rows ordered ahead.
Scores 91, 91 and 82 receive ranks 1, 1 and 3 when ordered from highest to lowest.
Row offset
A row offset is the number of ordered row positions between the current row and a position requested by an offset function.
An offset of 12 corresponds to a year only in a complete series with exactly one row per month.
ROW_NUMBER
ROW_NUMBER assigns each row a distinct sequential position within its partition's order, requiring tie-breakers for repeatable tied positions.
A unique order ID can decide which of two orders on the same date receives position 1.
ROWS frame
A ROWS frame chooses boundaries by individual ordered row positions, so a fixed row offset can span different amounts of elapsed time.
Two preceding sales observations may reach back four days when some dates have no rows.
Running maximum
A running maximum is the largest known measure in the frame from the partition's beginning through the current ordered position.
For daily values 10, 14 and 9, the running maximum is 10, 14 and 14.
Running total
A running total is a cumulative sum through each current position in an ordered group, with the frame deciding how ties contribute.
Order-level amounts 50, 30 and 20 produce cumulative values 50, 80 and 100 under a unique order.

S

Session
A session is a group of consecutive events belonging to the same activity period under a defined rule about the gap between events.
Under a more-than-30-minute rule, exactly 30 minutes of inactivity stays within the session.
Sort-compatible index
A sort-compatible index stores keys in an order that can supply a window's partition and sort sequence, potentially reducing sorting work.
An index beginning with store and sale date can help a report ordered within each store.
SQL dialect
An SQL dialect is a database system's supported syntax and behavior, including differences in functions, frames, arithmetic and ordering.
An interval RANGE query written for PostgreSQL needs adaptation before it can run in SQL Server.
Start flag
A start flag marks the first row of a run, allowing a cumulative sum of flags to give all rows in each run a common identifier.
A session's first event gets flag 1; later events get 0 until the inactivity rule starts another session.

T

Tie-breaker
A tie-breaker is an additional sort expression that determines positions among rows equal on earlier sort expressions.
Appending a unique primary key makes row-number assignments stable for equal timestamps.
Top N per group
A top N per group selection keeps leading rows or value levels independently within each group, using a ranking rule and a later filter.
Partitioning submissions by class lets the report select the best three from every class.
Trailing frame
A trailing frame ends at the current position and includes a bounded preceding span, using earlier information for each calculation.
A seven-row trailing total uses six preceding rows plus the current observation.

W

Window frame
A window frame is the subset of the current partition selected relative to the current row for aggregates and positional value functions.
A three-row moving sum uses a different frame on each successive row of the same partition.
Window function
A window function calculates a value from related rows and returns it alongside the current row, preserving that row's detail.
A salary report can show each employee beside the average salary for the employee's department.
Window order
A window order is the sequence specified inside OVER that determines ranking positions, offsets and ordered frame boundaries.
Ordering by sale date makes a running total accumulate chronologically within each store.

Y

Year-to-date total
A year-to-date total accumulates values within a calendar year, restarting at the next year and separately for each partitioned entity.
Partitioning by store and year keeps each store's January total separate from earlier years.

About this lesson

By StudeliReport a mistake

Make your own Study Materials

Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.

Get Started