CertSafari
    Databricks Certified Data Engineer Professional - October 9 onwards· Lessons

    Domain 3 · Lesson 18/45

    Spark SQL window functions: ranking, lag/lead and frames

    Apply advanced data transformations, including window functions, joins, and aggregations, using Spark SQL and PySpark to process large datasets.

    17 min read
    3% of exam
    7 sources
    Published 22 Oct 2026
    Docs as of 17 Oct 2026

    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.

    The three parts of a window specification
    ClauseWhat it decidesWhen it is omitted
    PARTITION BYThe group of rows the function operates onThe partition is all rows of the result
    ORDER BYThe order of rows within each partitionNot allowed for ranking functions, which must include ORDER BY
    window_frameA sliding subset of rows within the partition for aggregate or analytic functionsA 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.

    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.

    RANK per department: tied salaries share a rank and the next rank is skippedsql
    > 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    3

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

    PySpark Window spec with row_number within each categorypython
    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.

    LAG and LEAD per department, with LEAD supplying a default of 0 at the partition edgesql
    > 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     0

    Checkpoint 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?

    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.

    The same cumulative sum under ROWS and RANGE: the results differ only on the tied salariessql
    > 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  96000

    Most 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  72000

    Checkpoint 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?

    Sources23

    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.

    MIN as a window aggregate: every row is kept, and each shows its department's minimum so farsql
    > 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 21000

    A 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_distinct for the number of distinct values
    • approx_percentile for percentiles of numeric data
    • approx_top_k for 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?

    Sources14567

    Sources

    (7)

    Every claim above is drawn from one of these pages, quoted as it was written on the date shown.

    1. 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. 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. 3.
      “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. 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. 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. 6.
    7. 7.

    Continue to part 2 of 2

    Spark SQL joins, broadcast hints and grouped aggregations

    Spotted a mistake, or was something unclear? Tell us.