Chapter 7 · Lesson 6 of 6

Other Common Window Functions

Review other common window functions, including RANK, DENSE_RANK, NTILE, LEAD, FIRST_VALUE, and LAST_VALUE, and how frames affect them.

You have now seen the main shape of window functions: a function call followed by an OVER (...) clause.

The same window definition can be paired with several families of functions:

Aggregate window functions reuse aggregates you already know, but without collapsing rows:

SUM(...) OVER (...), AVG(...) OVER (...), MIN(...) OVER (...), MAX(...) OVER (...), and COUNT(...) OVER (...)

Use these for totals, running totals, moving averages, group averages beside detail rows, and percent-of-total calculations.

Ranking functions assign positions inside an ordered window:

ROW_NUMBER() gives every row a unique sequence number. RANK() gives tied rows the same rank and leaves gaps. DENSE_RANK() gives tied rows the same rank without gaps. NTILE(n) splits ordered rows into roughly equal buckets, such as quartiles with NTILE(4).

Use these for top-N queries, leaderboards, deduplication, and percentile-style grouping.

Offset functions compare a row to nearby rows:

LAG(...) looks backward. LEAD(...) looks forward.

Use these for change-over-time analysis, previous/next status, gaps between events, and month-over-month comparisons.

Value functions pick values from a window frame:

FIRST_VALUE(...) returns the first value in the current frame. LAST_VALUE(...) returns the last value in the current frame. NTH_VALUE(..., n) returns the nth value in the current frame.

These are powerful, but they depend heavily on the window frame. If LAST_VALUE surprises you, check whether your frame ends at the current row or at the end of the partition.

A useful rule of thumb: choose the function for the question, then choose PARTITION BY for the groups, ORDER BY for the sequence, and a frame when the exact row range matters.

This lesson is theory-focused. Read it, then mark it complete in the Learn SQL panel before moving on.

Open this lesson in the SQL editor

Lessons in Window Functions

Calculate totals, running sums, rankings, and previous-row comparisons with OVER and PARTITION BY while keeping every detail row.

  1. 01 · OVER Keeps the Detail Rows
  2. 02 · PARTITION BY Creates Mini Windows
  3. 03 · Running Totals with ORDER BY
  4. 04 · Ranking Rows with ROW_NUMBER
  5. 05 · Looking Back with LAG
  6. 06 · Other Common Window Functions

Related guides