What you will be able to do
- Write a window specification with PARTITION BY, ORDER BY and an explicit frame in Spark SQL or PySpark
- Choose between RANK, DENSE_RANK and row_number for ranking and deduplication, and use LAG/LEAD with a default value
- Predict how ROWS and RANGE frames, including the default frame, change running totals when ORDER BY values tie
- Choose between batch queries, materialized views, watermarked streaming aggregates, approximate functions and key salting when aggregating large datasets
Key concept
Window frame — A window frame is the set of rows inside the current row's partition that an aggregate or analytic window function actually reads. Once a window has an ORDER BY and no explicit frame, Spark uses a RANGE frame that runs from the start of the partition up to the current row's ORDER BY value, so rows that tie on that value all fall into the frame together.
1.What a window function computes
A window function returns one value for every input row, and it computes that value from a group of related rows called the window. A GROUP BY collapses each group into one output row. A window keeps every row and adds a column next to it. That is why windows are the standard tool for running totals, moving averages, rankings, and comparing a row with the row before it.
Every window function has the form function OVER (window_spec). The spec has three optional parts. PARTITION BY decides which rows belong together. ORDER BY sorts the rows inside each partition. The frame chooses a sliding subset of the partition for the function to read. The function itself comes from one of three classes: ranking functions such as RANK, analytic functions such as LAG, or ordinary aggregates such as SUM and AVG. An aggregate used as a window function cannot carry a FILTER clause, even though the same aggregate can take one inside a GROUP BY.
| Clause | What it decides | When it is omitted |
|---|---|---|
| PARTITION BY | The group of rows the function operates on | The partition is all rows of the result |
| ORDER BY | The order of rows within each partition | Not allowed for ranking functions, which must include ORDER BY |
| window_frame | A sliding subset of rows within the partition for aggregate or analytic functions | A default frame applies (see the frames section) |
If you leave out PARTITION BY, the query is still valid. The whole result becomes one partition, so a SUM(...) OVER (ORDER BY ts) gives a single running total across the entire table instead of one per store or customer. On a large dataset that also means every row ends up in the same window. Add a partition key whenever the business question is per entity.
Checkpoint 1 of 5· Match them up
Match each part of a window specification, or leaving one out, to its effect
Tap a term, then the definition that fits it.
PARTITION BY groups the rows, ORDER BY sorts them inside each group, and the frame narrows which rows the function reads. If you leave out PARTITION BY, the query does not fail and is not split by group. Every row falls into one partition, so you get a single running total across the whole table.
“If no PARTITION clause is specified the partition is comprised of all rows.”Source: docs.databricks.com
Sources1
2.Ranking, deduplication and lag/lead
Ranking functions number the rows of each partition according to the ORDER BY. That is why they must have one. They also refuse an explicit frame clause, because a rank depends on the whole ordered partition and not on a sliding subset of it.
> SELECT name,
dept,
RANK() OVER (PARTITION BY dept ORDER BY salary) AS rank
FROM employees;
Lisa Sales 10000 1
Alex Sales 30000 2
Evan Sales 32000 3
Fred Engineering 21000 1
Tom Engineering 23000 2
Chloe Engineering 23000 2
Paul Engineering 29000 4
Helen Marketing 29000 1
Jane Marketing 29000 1
Jeff Marketing 35000 3RANK leaves a gap after a tie, so Paul is 4th. DENSE_RANK does not, so on the same data Paul is 3rd. Use RANK for competition-style standings and DENSE_RANK when you want the 'top N distinct values'. Neither one can deduplicate, because tied rows get the same number.
row_number is the function for deduplication. It gives every row in a partition its own position in ORDER BY order, even when the ordering values tie. In the PySpark example below, the two identical (1, "a") rows still get different numbers. To keep one row per key, filter that column to 1.
from pyspark.sql import Window, functions as sf
df = spark.createDataFrame(
[(1, "a"), (1, "a"), (2, "a"), (1, "b"), (2, "b"), (3, "b")], ["id", "category"]
)
# Show row number ordered by id within each category partition
window = Window.partitionBy("category").orderBy("id")
df.withColumn("row_number", sf.row_number().over(window)).show()LAG and LEAD read the value from a row before or after the current one in the same ordered partition. Use them for period-over-period deltas or for spotting gaps between events. At the edge of a partition no such row exists. LAG(salary) then returns NULL for the lowest-paid person in each department. LEAD(salary, 1, 0) returns its third argument, 0, for the highest-paid. The offsets never cross a partition boundary, so Paul's lead is 0 and not Helen's salary from Marketing.
> SELECT name,
salary,
LAG(salary) OVER (PARTITION BY dept ORDER BY salary) AS lag,
LEAD(salary, 1, 0) OVER (PARTITION BY dept ORDER BY salary) AS lead
FROM employees;
Lisa 10000 NULL 30000
Alex 30000 10000 32000
Evan 32000 30000 0
Fred 21000 NULL 23000
Chloe 23000 21000 23000
Tom 23000 23000 29000
Paul 29000 23000 0
Helen 29000 NULL 29000
Jane 29000 29000 35000
Jeff 35000 29000 0Checkpoint 2 of 5· Check yourself
A pipeline review flags one of these window expressions as invalid in Spark SQL. Which one breaks the rules for its function class?
Ranking functions need an ORDER BY but do not accept a window_frame clause, because a rank depends on the whole ordered partition. RANK without PARTITION BY is valid and treats the whole result as one partition. LAG and LEAD with a partition and an ORDER BY are valid too.
“ranking_function Any of the Ranking window functions. If specified the window_spec must include an ORDER BY clause, but not a window_frame clause.”Source: docs.databricks.com
Sources1
3.Frames: ROWS versus RANGE, and the default you get
The frame decides which rows of the partition an aggregate actually reads. It has a mode, ROWS or RANGE, plus a start and an end. The start and end can each be UNBOUNDED PRECEDING, an offset PRECEDING, CURRENT ROW, an offset FOLLOWING, or UNBOUNDED FOLLOWING. If you give only a start, the frame ends at the current row.
ROWS counts physical rows. ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING averages three neighbouring rows, which is a moving average. ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING sums from this row to the end of the partition. For Fred, the lowest-paid engineer, that gives 96000, the whole department. RANGE works on values instead. The offsets apply to the current row's ORDER BY value, so every row whose value falls inside the bounds is included, however many rows that is.
> SELECT name,
salary,
SUM(salary) OVER (ORDER BY salary
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS rows_total,
SUM(salary) OVER (ORDER BY salary
RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS range_total
FROM employees
WHERE dept = 'Engineering';
Fred 21000 21000 21000
Chloe 23000 44000 67000
Tom 23000 67000 67000
Paul 29000 96000 96000Most running-total surprises come from the default frame. If a window has an ORDER BY and no frame, Spark uses RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. If it has no ORDER BY, the frame is the entire partition. Take a per-store running total ordered by sale_ts. Two sales with the same timestamp are peers under RANGE, so both rows jump to include both amounts at once. Spark has not dropped or merged any rows, and it has not changed modes. The default frame is behaving as defined. If you want the total to grow one row at a time, write ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW explicitly.
RANGE has strict rules. It needs an ORDER BY, and that ORDER BY must be a single expression. Otherwise Databricks raises DATATYPE_MISMATCH.RANGE_FRAME_WITHOUT_ORDER or DATATYPE_MISMATCH.RANGE_FRAME_MULTI_ORDER. PySpark has the same split: Window.rowsBetween(start, end) uses row offsets and Window.rangeBetween(start, end) uses value offsets. Pass the boundaries as Window.unboundedPreceding, Window.currentRow and Window.unboundedFollowing.
Checkpoint 3 of 5· Fill the gap
In this output, Chloe and Tom tie on salary but get different running totals. Which frame mode completes the query?
> SELECT name,
dept,
salary,
SUM(salary) OVER (PARTITION BY dept ORDER BY salary
? BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_total
FROM employees;
Fred Engineering 21000 21000
Chloe Engineering 23000 44000
Tom Engineering 23000 67000
Paul Engineering 29000 96000
Jane Marketing 29000 29000
Jeff Marketing 35000 64000
Lisa Sales 10000 10000
Alex Sales 30000 40000
Evan Sales 32000 72000ROWS counts physical rows, so the total grows one row at a time, even across tied salaries: 44000 for Chloe, then 67000 for Tom. RANGE treats the two 23000 rows as peers, so both would show 67000. That is also what you get when you leave the frame out. Spark only accepts ROWS or RANGE as the frame mode.
Source: docs.databricks.comCheckpoint 4 of 5· Exam question
A pipeline computes a running total of revenue per store_id ordered by sale_ts using:
SELECT store_id, sale_ts, revenue,
SUM(revenue) OVER (PARTITION BY store_id ORDER BY sale_ts) AS running_total
FROM sales
When two rows share the exact same sale_ts for a store, the running total for both rows jumps to include both rows' revenue at once, instead of accumulating one row at a time. Why does this happen?
Correct answer: A — Omitting an explicit frame clause on an ordered window defaults to a RANGE frame from unbounded preceding to the current row's ORDER BY value, so peer rows sharing that value are all included together.
- A. Correct. With ORDER BY defined and no explicit frame, Spark SQL defaults to a RANGE frame from unbounded preceding to the current row, and RANGE frames include every row that ties on the ORDER BY value as peers, so all same-timestamp rows get the same, larger running total together.
- B. Incorrect. Spark does not dynamically swap frame types based on detected duplicates; the frame type is fixed by whether ORDER BY and an explicit frame clause are present, not by the data values encountered at runtime.
- C. Incorrect. Window functions never deduplicate or merge input rows; every input row is preserved in the output with its own computed value, so no row is dropped or redistributed.
- D. Incorrect. Missing a tie-breaker affects which of several equally valid row orderings Spark may choose among peers, but it does not change the frame boundary semantics that cause peers to be summed together under RANGE.
4.Aggregations on large and streaming datasets
An aggregate function such as SUM, MIN or COUNT reduces many rows to one value, and Spark SQL lets it do that in two shapes. Under GROUP BY, which has its own lesson, each group collapses to a single output row. Under OVER, the same aggregate keeps every row and reports the result for that row's window. In the query below, MIN(salary) with an ORDER BY returns the lowest salary seen so far in each department, so every Sales row shows Lisa's 10000.
> SELECT name,
dept,
salary,
MIN(salary) OVER (PARTITION BY dept ORDER BY salary) AS min
FROM employees;
Lisa Sales 10000 10000
Alex Sales 30000 10000
Evan Sales 32000 10000
Helen Marketing 29000 29000
Jane Marketing 29000 29000
Jeff Marketing 35000 29000
Fred Engineering 21000 21000
Tom Engineering 23000 21000
Chloe Engineering 23000 21000
Paul Engineering 29000 21000A batch aggregate recomputes the statistic over every record in the source each time it runs, so its cost grows with the table. That is the default for an ad hoc SQL query or a DataFrame job, and Databricks uses metadata and optimizations to keep it fast. Still, a dashboard that reads the same daily revenue figures every morning should not rescan a billion-row fact table each time. A materialized view stores the aggregate, tracks changes in the source and updates the values on refresh. Its results match what a fresh batch query would return. Incremental refresh needs serverless compute, because on classic compute a materialized view is fully recomputed on every refresh. Non-deterministic functions in the query also stop it from refreshing incrementally.
Streaming aggregates are stateful, and a watermark is what keeps that state finite. The engine tracks the records it has seen and recomputes results as new data arrives. A watermark is declared on an event-time column with a delay, such as .withWatermark("impression_time", "3 minutes"), and it is what lets the engine decide that old state can no longer be matched and evict it. Picture a per-device count over a Kafka stream with no watermark. It runs fine on day one, slows down through the week and eventually fails with out-of-memory errors, because nothing ever tells the engine to discard state, so it only grows. A stateful aggregate is also the wrong tool for statistics over an entire dataset. Use a materialized view for those.
Approximate aggregates trade a little precision for speed and lower cost. For a question like "roughly how many distinct users came yesterday", an exact count is rarely worth its price. Spark SQL has three native approximation functions:
approx_count_distinctfor the number of distinct valuesapprox_percentilefor percentiles of numeric dataapprox_top_kfor the most frequent values
TABLESAMPLE with a sample percent draws a random sample that you can aggregate. LIMIT cannot stand in for it. It gives a quick snapshot, but the rows are not random and need not come from across the whole dataset, so an average over LIMIT 10000 may describe one file rather than the table.
Skew is the first thing to slow down a large aggregation. If a few key values hold most of the rows, a few tasks do most of the work while the rest of the cluster sits idle. When the skew appears during the computation, salt the hot keys. Append a random bucket suffix to each key, aggregate by the salted key, then aggregate those partial results again by the original key. When the skew comes from how a stored table is laid out, use liquid clustering instead. Liquid clustering is a Delta table layout feature: you choose clustering keys, the table's data is organized around them, and you can redefine those keys later without rewriting existing data. Databricks recommends it for tables with a significantly skewed data distribution.
Checkpoint 5 of 5· Check yourself
A streaming table counts events per device with a groupBy and no watermark. Each day its micro-batches take longer, and after a week the job fails. What explains this?
A streaming aggregate is stateful. Without a watermark nothing tells the engine when it can discard old state, so the state keeps growing until processing slows and memory runs out.
“Omitting a watermark from a stateful aggregate query results in state information building up infinitely over time.”Source: docs.databricks.com
Sources
(7)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.
“calculate a return value for each row based on the group of rows”
↩︎ What a window function computes“If no PARTITION clause is specified the partition is comprised of all rows.”
↩︎ What a window function computes“If specified the function must not include a FILTER clause.”
↩︎ What a window function computes“If specified the window_spec must include an ORDER BY clause, but not a window_frame clause.”
↩︎ Ranking, deduplication and lag/lead“accessing the value of rows given the relative position of the current row”
↩︎ Ranking, deduplication and lag/lead“aggregate_function Any of the Aggregate functions.”
↩︎ Aggregations on large and streaming datasets“If specified the window_spec must include an ORDER BY clause, but not a window_frame clause.”
↩︎ Exam trap 2“If no PARTITION clause is specified the partition is comprised of all rows.”
↩︎ Exam trap 3“Paul Engineering 29000 4”
↩︎ Prediction“ranking_function Any of the Ranking window functions. If specified the window_spec must include an ORDER BY clause, but not a window_frame clause.”
↩︎ Checkpoint - 2.
“When ordering is defined, a growing window frame (rangeFrame, unboundedPreceding, currentRow) is used by default.”
↩︎ Frames: ROWS versus RANGE, and the default you get“When ordering is not defined, an unbounded window frame (rowFrame, unboundedPreceding, unboundedFollowing) is used by default.”
↩︎ Frames: ROWS versus RANGE, and the default you get“When ordering is defined, a growing window frame (rangeFrame, unboundedPreceding, currentRow) is used by default.”
↩︎ Key concept - 3.https://docs.databricks.com/aws/en/sql/language-manual/sql-ref-syntax-window-functions-frameOfficial docs
“If not specified, the frame stops at the CURRENT ROW.”
↩︎ Frames: ROWS versus RANGE, and the default you get“If the ORDER BY clause has multiple expressions, Databricks raises DATATYPE_MISMATCH.RANGE_FRAME_MULTI_ORDER.”
↩︎ Frames: ROWS versus RANGE, and the default you get“Unlike ROWS mode, RANGE groups rows with equal `ORDER BY` values together.”
↩︎ Exam trap 1 - 4.
“Batch aggregation latency and compute costs can increase as data size increases”
↩︎ Aggregations on large and streaming datasets“Materialized views automatically track changes in the data source and apply appropriate updates to aggregate values on refresh.”
↩︎ Aggregations on large and streaming datasets“Omitting a watermark from a stateful aggregate query results in state information building up infinitely over time.”
↩︎ Aggregations on large and streaming datasets“using approximation for aggregates can accelerate query processing and reduce costs when you don't require precise results.”
↩︎ Aggregations on large and streaming datasets“does not introduce randomness, or guarantee that sampling is distributed across the dataset”
↩︎ Exam trap 4 - 5.
“On classic compute, materialized views are always fully recomputed, which increases refresh costs.”
↩︎ Aggregations on large and streaming datasets“allowing it to evict state that can no longer be matched”
↩︎ Aggregations on large and streaming datasets“salt highly-skewed keys by appending a random bucket suffix before grouping and aggregating in two stages.”
↩︎ Aggregations on large and streaming datasets - 6.https://docs.databricks.com/aws/en/lakehouse-architecture/performance-efficiency/best-practicesOfficial docs
“It also allows you to redefine clustering keys without rewriting existing data”
↩︎ Aggregations on large and streaming datasets - 7.
“use liquid clustering, which is suited to tables with heavy data skew.”
↩︎ Aggregations on large and streaming datasets