CertSafari
    Databricks Certified Associate Developer for Apache Spark· Lessons

    Domain 5 · Lesson 27/32

    Streaming selection, windows and aggregations in Spark

    Perform basic operations on Streaming DataFrames and Streaming Datasets, such as selection, projection, window and aggregation.

    17 min read
    2.5% of exam
    8 sources
    Published 21 Oct 2026
    Docs as of 17 Oct 2026

    What you will be able to do

    • Apply select, filter and column expressions to a streaming DataFrame and name the kind of operation a stream cannot support
    • Write a streaming aggregation grouped by a key, by an event-time window, or by both
    • Choose between tumbling, sliding and session windows and write the matching window() or session_window() call
    • Apply the rules for window time columns and duration strings
    • Pick an output mode for an aggregated stream and explain why append mode depends on a watermark

    Key concept

    Event-time window as a grouping key — window() assigns each row to one or more time buckets, based on a timestamp column inside the data. Grouping by that bucket, alone or together with ordinary keys, turns a stream into a set of per-window aggregates. Spark keeps each aggregate in state and updates it as new rows arrive.

    1.Selection and projection work on a stream unchanged

    A streaming DataFrame accepts the same column operations as a static one. select projects expressions into new columns, filter (or its alias where) keeps the rows that match a condition, and withColumn, alias and the built-in SQL functions all work the same way. The Structured Streaming incremental programming model runs your batch-style query again on each new slice of input. This means a projection written for a table needs no changes to run against spark.readStream.

    A projection on a streaming DataFrame: keep every column and add two derived onespython
    from pyspark.sql.functions import col, current_timestamp
    
    transformed_df = (raw_df.select(
        "*",
        col("_metadata.file_path").alias("source_file"),
        current_timestamp().alias("processing_time")
        )
    )

    Nothing runs when this line executes. transformed_df is a plan describing how to load and transform each record as it arrives. A row is processed only when a sink starts the query.

    Selections and projections are stateless. Each output row depends only on the input row it came from, so Spark does not need to remember anything between micro-batches. Aggregations are different, as the next section shows.

    Some operations cannot run on a stream at all. A source is treated as unbounded, so any operation that needs to see every row before it can produce output has no point at which it could finish. Sorting the whole stream is the standard example, because it would mean ordering an infinite set of rows. On an exam, if a streaming query fails and its only unusual step is a global sort, the stream's unbounded input is the cause.

    Checkpoint 1 of 9· Fill the gap

    This projection runs on a streaming DataFrame. It keeps every column and adds two derived ones. Which method completes it?

    from pyspark.sql.functions import col, current_timestamp
    
    transformed_df = (raw_df. ? (
        "*",
        col("_metadata.file_path").alias("source_file"),
        current_timestamp().alias("processing_time")
        )
    )

    Checkpoint 2 of 9· Check yourself

    A query reads from spark.readStream, applies filter, adds a column with withColumn, and then calls orderBy on the whole stream. It fails when started. What is the most likely cause?

    Sources123

    2.Grouped aggregations hold state across micro-batches

    groupBy(...).count(), .agg(sum(...)) and other grouped aggregations are valid on a stream, and they do not need a time window. readings.groupBy("sensorId").count() is a legitimate streaming aggregation. It keeps a running count per sensor and adds to it with every micro-batch. Spark does not reject plain key grouping, and the key can be any groupable type, so no cast is needed.

    The cost is state. To update a count instead of recomputing it from scratch, Spark has to keep the current value for every group it has ever seen. That makes aggregation a stateful operator, in the same family as distinct, dropDuplicates and stream-stream joins. The mechanics of the state store are covered in Stateful operators and the StateStore. What matters here is that a key-only aggregation never closes a group. A sensor that reported once a year ago still has a row in state, and the number of rows grows with every new key.

    Grouping by an event-time window as well as by a key is what lets that state be bounded. Once a window is far enough in the past, its aggregate can be finalized and removed from state. A plain key has no such endpoint. The next two sections build on this difference.

    Checkpoint 3 of 9· Check yourself

    Suppose readings.groupBy("sensorId").count() runs on a streaming DataFrame with no window() and no watermark. What does Spark do?

    Sources45

    3.Tumbling, sliding and session windows

    window(timeColumn, windowDuration, slideDuration) assigns each row to time buckets based on a timestamp in the data. You place the call inside groupBy, usually next to ordinary key columns. The number of arguments decides the window type.

    Tumbling windows have a fixed size and do not overlap, so every row lands in exactly one window. You get them by passing only a window duration, for example window("event_time", "10 minutes"). Use them for discrete period totals such as hourly sales or a count for each 10-minute period.

    A 5-minute tumbling window combined with a key column, counted per idpython
    from pyspark.sql.functions import window
    
    (df
      .withWatermark("event_time", "10 minutes")
      .groupBy(
        window("event_time", "5 minutes"),
        "id")
      .count()
    )

    Sliding windows add a third argument, the slide. A new window starts every slideDuration, and each window covers windowDuration. When the slide is shorter than the window, windows overlap and one row counts toward several of them. This gives a rolling figure, like a moving average. A click count over 20-minute periods refreshed every 5 minutes is window(click_time, "20 minutes", "5 minutes"), and each click falls into four overlapping windows. The order of the arguments matters: the window length comes first and the slide second. The slide must be less than or equal to the window length, so window(t, "5 minutes", "20 minutes") is invalid. A slide equal to the window length gives non-overlapping windows, which is the same result as a tumbling window, so it is not a way to get overlap.

    A sliding window: 6-hour totals that advance by 1 hourpython
    from pyspark.sql.functions import window, sum
    
    rolling_sales = (orders
      .withWatermark("timestamp", "1 hour")
      .groupBy(window("timestamp", "6 hours", slideDuration="1 hour"))
      .agg(sum("amount").alias("total_sales"))
    )

    Session windows use a different function, session_window(timeColumn, gapDuration), and they have no fixed size. A session opens when a row arrives, and each later row that arrives within the gap extends it. The session closes after a gap with no rows. Sessions fit bursts of activity separated by idle time, such as one user's page views. They are the wrong choice when the requirement names a fixed period such as "every 10 minutes".

    Session windows per user with a 30-minute inactivity gappython
    from pyspark.sql.functions import session_window, sum
    
    sessionized_page_views = (activity
      .withWatermark("timestamp", "1 hour")
      .groupBy("user_id", session_window("timestamp", gapDuration="30 minutes"))
      .agg(sum("page_views").alias("total_page_views"))
    )
    How the three window types differ
    Window typeCallWindows overlap?Windows per rowFits
    Tumblingwindow("timestamp", "1 hour")NoExactly oneHourly sales totals
    Slidingwindow("timestamp", "6 hours", slideDuration="1 hour")Yes, when slide < windowPossibly severalSales over a rolling 6-hour period
    Sessionsession_window("timestamp", gapDuration="30 minutes")No fixed size; closes after the gapOne session per keyA user's page views between idle periods

    Checkpoint 4 of 9· Match them up

    Each call below is placed inside groupBy on a streaming DataFrame. Match each call to the windows it produces.

    Tap a term, then the definition that fits it.

    Checkpoint 5 of 9· Exam question

    A monitoring pipeline reads a streaming DataFrame logins with an event-time column event_time and needs 10-minute tumbling windows that report a fresh count for every 10-minute period with no overlap between consecutive windows. Which line correctly defines this windowed aggregation? result = logins.groupBy( ___ ).count()

    Checkpoint 6 of 9· Exam question

    A dashboard needs a running count of clicks per page over 20-minute periods, refreshed every 5 minutes so overlapping windows continuously update as new data arrives, similar to a moving average. Which window() call produces this behavior? clicks.groupBy( ___, clicks.page ).count()

    Sources56

    4.Rules for the time column and window durations

    The time column must be a timestamp. Both window() and session_window() need a TimestampType or TimestampNTZType column. A string column such as "2024-05-01 10:00" or an epoch number has to be converted first. If you want windows based on arrival time instead of event time, window on current_timestamp().

    Durations are strings made of a number and a unit, for example '10 minutes', '1 second' or '1 day 12 hours'. The valid units are week, day, hour, minute, second, millisecond and microsecond. Each duration is a fixed length of time, not a calendar period, so 1 day is always 86,400,000 milliseconds. That is also why windows measured in months are not supported.

    Window boundaries include the start and exclude the end. An event at 12:05 belongs to [12:05, 12:10) and not to [12:00, 12:05). By default, windows line up with 1970-01-01 00:00:00 UTC. The optional startTime argument shifts them, so hourly windows with a startTime of 15 minutes run 12:15–13:15, 13:15–14:15 and so on.

    The result column is a struct named window with nested start and end timestamps. Select window.start and window.end when the sink needs flat columns.

    Two more rules apply when a watermark is involved. The window must be built on the same timestamp column that the watermark is declared on. Inside groupBy() and window(), refer to that column by name ("event_time" or col("event_time")) so Spark keeps the event-time marker that the watermark relies on.

    Checkpoint 7 of 9· Check yourself

    In a streaming DataFrame, ts is a TimestampType column and ts_str is a StringType column with values like "2024-05-01 10:00". Which window() call inside groupBy is valid as written?

    Sources567

    5.Output modes after an aggregation

    Adding an aggregation limits which output modes you can use. All three modes are covered in Output modes: append, update, complete. For aggregations, two of their definitions matter most. Complete mode works only with streaming aggregations and rewrites every result row on each trigger. Append mode, the default, emits a row only once that row can no longer change, and stateful operators use the watermark to decide when that point has come.

    A running count per sensorId can always go up again, so append mode never has a moment when the row is safe to write. Neither the sink nor the missing window is the problem; the issue is that Spark cannot tell when a group is final. Two fixes work. For a running total, use update mode (emit the rows that changed) or complete mode (emit everything). For finalized results, group by an event-time window and declare a watermark. A watermark (withWatermark) sets how late data may arrive, and when it moves past a window's end, that window is closed and append mode can emit it.

    Here is a worked example: hourly revenue with a 15-minute watermark. The first micro-batch contains $15 at 2:40pm, $10 at 2:30pm and $30 at 3:10pm, so the watermark is 3:10 − 15 min = 2:55pm. Then $20 arrives at 3:20pm, and the watermark moves to 3:05pm.

    What each output mode emits for the hourly revenue example
    Output modeAfter batch 1 (watermark 2:55pm)After the $20 at 3:20pm (watermark 3:05pm)
    AppendNothing: both [2pm, 3pm] and [3pm, 4pm] could still change[2pm, 3pm]: $25, because the watermark has passed the window's end
    UpdateBoth windows, since both changed[3pm, 4pm]: $50, the only window that changed
    CompleteAll windowsAll windows

    The choice affects state size as well as how soon results appear. In append and update modes, the state for windows the watermark has passed is dropped. Complete mode never drops aggregation state, because it has to rewrite the whole result on every trigger. Append mode always waits at least the watermark delay before writing a row. A 1-hour watermark therefore means at least a 1-hour delay downstream. In return, each window is written exactly once, which suits sinks that act on every write. A live dashboard that needs fresh numbers is better served by update mode.

    Checkpoint 8 of 9· Match them up

    A windowed aggregation with a watermark runs under each of the output modes below. Pair each mode with what it writes and what happens to its aggregation state.

    Tap a term, then the definition that fits it.

    Checkpoint 9 of 9· Exam question

    An engineer writes the following on a streaming DataFrame readings with columns sensorId and value: counts = readings.groupBy("sensorId").count() counts.writeStream.outputMode("append").format("console").start() Running this raises an AnalysisException about the output mode. What is the most likely cause?

    Sources85

    Sources

    (8)

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

    1. 1.
      “Structured Streaming supports most transformations that are available in Databricks and Spark SQL.”
      ↩︎ Selection and projection work on a stream unchanged
      “some transformations are not supported in Structured Streaming workloads because they would require sorting an infinite number of items.”
      ↩︎ Selection and projection work on a stream unchanged
      “some transformations are not supported in Structured Streaming workloads because they would require sorting an infinite number of items”
      ↩︎ Checkpoint
    2. 3.
      “Stateless queries process rows without retaining state. Stateful queries maintain intermediate state for aggregations, joins, and deduplication.”
      ↩︎ Selection and projection work on a stream unchanged
    3. 4.
      “Stateful operations include streaming aggregation, distinct, dropDuplicates, stream-stream joins, and custom stateful applications.”
      ↩︎ Grouped aggregations hold state across micro-batches
    4. 5.
      “Streaming queries accumulate state data over time. Watermarks automatically remove old state data to prevent memory errors and increased processing latency.”
      ↩︎ Grouped aggregations hold state across micro-batches
      “Tumbling windows are fixed-size with non-overlapping intervals. Each input row belongs to exactly one window.”
      ↩︎ Tumbling, sliding and session windows
      “Sliding windows are fixed-size with intervals that can overlap. A single row can belong to multiple windows.”
      ↩︎ Tumbling, sliding and session windows
      “Use current_timestamp() to define windows based on processing time rather than event time.”
      ↩︎ Rules for the time column and window durations
      “reference columns by name, "<colName>" or col("<colName>"), to ensure the event time marker is preserved.”
      ↩︎ Rules for the time column and window durations
      “Aggregation state isn't dropped. The query rewrites the target table for each trigger.”
      ↩︎ Output modes after an aggregation
      “A count is collected for each id observed for each non-overlapping 5 minute window.”
      ↩︎ Key concept
      “slideDuration must be less than or equal to the windowDuration.”
      ↩︎ Exam trap 2
      “Session windows have no fixed size. A window opens when a row arrives and closes after a gap duration that contains no new rows.”
      ↩︎ Exam trap 3
      “The timeColumn argument for window() and session_window() must be of TimestampType or TimestampNTZType.”
      ↩︎ Exam trap 4
      “slideDuration must be less than or equal to the windowDuration.”
      ↩︎ Checkpoint
      “You can set window durations from microseconds up to days. Month durations and longer are not supported.”
      ↩︎ Checkpoint
      “Complete | Aggregation state isn't dropped. The query rewrites the target table for each trigger.”
      ↩︎ Checkpoint
    5. 6.
      “If the slideDuration is not provided, the windows will be tumbling windows.”
      ↩︎ Tumbling, sliding and session windows
      “Valid interval strings are 'week', 'day', 'hour', 'minute', 'second', 'millisecond', 'microsecond'.”
      ↩︎ Rules for the time column and window durations
      “For example, 1 day always means 86,400,000 milliseconds, not a calendar day.”
      ↩︎ Rules for the time column and window durations
      “Windows in the order of months are not supported.”
      ↩︎ Rules for the time column and window durations
      “Window starts are inclusive but the window ends are exclusive, e.g. 12:05 will be in the window [12:05,12:10) but not in [12:00,12:05).”
      ↩︎ Rules for the time column and window durations
      “The startTime is the offset with respect to 1970-01-01 00:00:00 UTC with which to start window intervals.”
      ↩︎ Rules for the time column and window durations
      “The output column will be a struct called 'window' by default with the nested columns 'start' and 'end'”
      ↩︎ Rules for the time column and window durations
    6. 7.
      “The window must be based on the same timestamp column as the watermark”
      ↩︎ Rules for the time column and window durations
    7. 8.
      “Complete mode only works with streaming aggregations.”
      ↩︎ Output modes after an aggregation
      “In this mode, operators only emit rows that don't change in future triggers. Stateful operators use the watermark to determine when this happens.”
      ↩︎ Output modes after an aggregation
      “By the definition of the watermark, that window can no longer change, so it emits the [2pm, 3pm] window.”
      ↩︎ Output modes after an aggregation
      “Append mode forces stateful operators to emit results only after stateful results are finalized, which is at least as long as your watermark delay.”
      ↩︎ Output modes after an aggregation
      “Append mode forces stateful operators to emit results only after stateful results are finalized, which is at least as long as your watermark delay.”
      ↩︎ Exam trap 1

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