CertSafari
    Databricks Certified Associate Developer for Apache Spark· Lessons

    Domain 1 · Lesson 6/32

    Transformations, actions and lazy evaluation in Spark

    Describe the execution patterns of the Apache SparkTM engine, including actions, transformations, and lazy evaluation.

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

    What you will be able to do

    • Classify common DataFrame operations as transformations or actions and predict whether a line of code submits a Spark job
    • Explain why deferring execution lets the optimizer rewrite the whole plan before any data is read
    • Identify which inserted line actually forces an intermediate DataFrame to be computed, and which only inspect the plan or schema
    • Explain why every action re-runs the full lineage and why production pipelines end in a single write
    • Distinguish lazy execution, which all Spark applies, from lazy analysis, which applies only under Spark Connect

    Key concept

    Lazy evaluation — Transformations only add steps to a logical plan and return a new DataFrame. No data is read or computed until an action asks for a concrete result, and then Spark optimizes and runs the whole plan at once.

    1.Transformations build a plan, actions run it

    Every Spark operation falls into one of two kinds. A transformation adds processing logic to a plan and returns a new DataFrame. An action asks for a result, whether that is printing rows, returning a value to the driver or writing to storage. Only actions make the cluster do any work. A reader who can tell the two apart can tell exactly when a notebook cell will start a Spark job and when it will finish in milliseconds having done nothing.

    The transformation category is wider than most people expect. It includes reading data, joins, aggregations and type casting, as well as filter, select and sort. The cost or complexity of an operation doesn't change its kind. A groupBy(...).agg(...) that will eventually shuffle the whole dataset is still a transformation, and writing it down does not materialize its parent DataFrame. Reading is lazy too: spark.read...load(path) doesn't touch the files and only records where the data lives.

    Actions are the operations that need a concrete answer. Some display output (show, display), some bring rows back (take(n), first, head, collect), some write to a data source (saveAsTable), and some are aggregations that return a number, such as count. That last group is the one to watch: df.groupBy(...).agg(...) is a transformation, but df.count() is an action and starts a job right away.

    Common operations and whether they trigger computation
    OperationKindWhat happens when the line runs
    spark.read ... load(path), spark.table(name)TransformationA plan node pointing at the source is recorded; no data is loaded
    filter, select, join, groupBy(...).agg(...), sortTransformationA new DataFrame with a longer plan is returned
    repartitionTransformationA redistribution step is added to the plan
    show, displayActionThe plan executes and rows are printed
    collect, take(n), first, headActionThe plan executes and rows return to the driver
    countAction (aggregation)The plan executes and a number returns to the driver
    saveAsTableAction (write)The plan executes and results are written to the target
    A chain of four transformations; only the final display call triggers executionpython
    df_chained = (
        df_order.filter(col("o_orderstatus") == "F")
        .groupBy(col("o_orderpriority"))
        .agg(count(col("o_orderkey")).alias("n_orders"))
        .sort(col("n_orders").desc())
    )
    
    display(df_chained)

    What Spark keeps between transformations is a set of instructions, not data. A DataFrame variable holds a logical query against a data source rather than an in-memory result, and that is the main difference from pandas, which executes each step eagerly. Spark doesn't run transformations in the background, cache their output or hold copies on the driver. If a cell contains only transformations, it submits no job and raises no execution error. The plan sits there until an action asks for it.

    Checkpoint 1 of 8· Match them up

    A notebook cell contains each of these lines. Match each line to what happens when it runs.

    Tap a term, then the definition that fits it.

    Checkpoint 2 of 8· Exam question

    Which statement correctly describes why Apache Spark defers execution of .filter(), .select(), and other DataFrame transformations until an action such as .count() or .show() is called?

    Checkpoint 3 of 8· Exam question

    A data engineer runs the following code in a Databricks notebook cell: df = spark.read.parquet("/mnt/sales/transactions") filtered = df.filter(df.amount > 1000) grouped = filtered.groupBy("region").sum("amount") No further code is executed in this cell. What happens when this cell finishes running?

    Sources123

    2.Watching laziness line by line

    The clearest way to see laziness is to follow a three-line program and ask, after each line, what the cluster has done. The program below uses an RDD (resilient distributed dataset), a collection spread across the cluster that supports the same two kinds of operation as a DataFrame: transformations such as map and actions such as reduce. An RDD is created through sc, the SparkContext, rather than through the spark session that DataFrames use. In this example the answer is nothing until the third line.

    A base dataset, a transformation and an actionpython
    lines = sc.textFile("data.txt")
    lineLengths = lines.map(lambda s: len(s))
    totalLength = lineLengths.reduce(lambda a, b: a + b)

    After line one, lines is only a pointer to the file and nothing has been loaded. After line two, lineLengths is defined but not computed. Line three calls reduce, which is an action. Only then does Spark split the work into tasks on separate machines. Each machine runs its share of the map plus a local reduction, and only the small answers go back to the driver. DataFrames work the same way: filter, select and groupBy play the role of map, and count or a write plays the role of reduce.

    DataFrames are also immutable, and that matters when you want to time or check an intermediate step. Each transformation leaves its input unchanged and returns a new DataFrame, which you assign to a variable. Reassigning a variable to cleaned.select("*") or cleaned.repartition(8) only makes a longer plan, and no job runs. To actually evaluate an intermediate step, call an action on it. For example, print(cleaned.count()) runs every transformation behind cleaned at that point, separately from anything defined afterwards.

    Two kinds of calls look as if they do work, but they never execute the data pipeline. explain() only displays the logical or physical plans Spark would use, so it describes work without doing it. Schema inspection, such as df.schema or df.columns, needs the plan to be *analyzed*, meaning column names and types are resolved. It doesn't need the plan to be *executed*. In Spark Classic, the mode that runs without Spark Connect, that analysis happens eagerly as the plan is built, so asking for the schema reads metadata only and runs no job.

    Checkpoint 4 of 8· Check yourself

    You want to time only the cleaning steps behind cleaned in Spark Classic, before any later transformations are added. Which line actually runs those steps?

    Checkpoint 5 of 8· Exam question

    A developer wants to force Spark to materialize an intermediate DataFrame so its execution time can be measured separately from the rest of the pipeline, using the notebook cell below: cleaned = raw_df.dropDuplicates().filter(col("status") == "active") # ADD A LINE HERE to force execution and print row count final = cleaned.join(other_df, "id") Which line, inserted where indicated, forces Spark to execute the transformations that build cleaned at that point in the notebook, independent of the later join?

    Sources4356

    3.Why waiting pays off: Catalyst optimizes the whole plan

    Laziness exists so that the optimizer can see the whole query before deciding how to run it. Spark's query optimizer, Catalyst, plans each query. Because no transformation runs as soon as it is written, Catalyst gets the complete chain from source to action and can choose the most efficient physical plan for all of it, instead of running the steps one by one in the order they were typed.

    The plan goes through several stages, and EXPLAIN EXTENDED (or df.explain()) shows each one:

    1. A parsed logical plan, which is unresolved and comes straight from the query.
    2. An analyzed logical plan, where unresolved column and table references become fully typed objects.
    3. An optimized logical plan, produced by applying a set of optimization rules.
    4. A physical plan, which describes how the work will actually run on the cluster.

    Seeing the whole plan lets the optimizer change what work is done, not only the order of it. Predicate pushdown is the standard example: the engine pushes filter conditions down to the storage layer, so data that can't match is skipped instead of being read and then thrown away. A filter written after a join can only be applied at the scan because Spark hadn't read anything when the filter was declared. The RDD example shows the same benefit on a small scale: Spark knows the mapped dataset only feeds a reduce, so it returns just the reduced result to the driver and never the larger mapped dataset.

    Every action marks the edge of what can be optimized together. The optimizer considers all transformations triggered by a given action at once, so an action in the middle of a pipeline splits it into separately optimized pieces. That is why stray show or count calls in production code cost more than the time they take to print.

    Checkpoint 6 of 8· Check yourself

    A production job reads orders, joins customers, calls show() on the joined DataFrame to preview it, then filters the result and writes it with saveAsTable. What does the show() call in the middle do to how Spark optimizes the job?

    Sources735841

    4.Every action recomputes the plan

    An action doesn't leave results behind for the next action. A DataFrame is a plan, so each action sends that whole plan back to the source: it reads the files again, joins again and aggregates again. In exploratory work that is usually fine. In a pipeline, a count() added for logging followed by a write runs the full computation twice.

    When several actions really do need the same intermediate result, caching is the fix. Persisting a DataFrame keeps it on the cluster after it is first computed, so later actions start from it instead of the source. The mechanics are covered in cache(), persist() and storage levels. Caching has a cost, though. Like preview results, a manual cache in a production pipeline can interrupt whole-plan optimization and raise both cost and latency, so use it only where reuse actually happens.

    The production rule follows from this: a pipeline should normally end in one action, the write. Every other action is either a duplicate computation or a break in optimization. Actions such as collect, take and toPandas are a separate case. Their results come back to the driver instead of going to storage, which is useful for inspection but is not how a pipeline should deliver its output. See Bringing rows to the driver (collect, take, toLocalIterator, toPandas).

    Checkpoint 7 of 8· Check yourself

    In a scheduled pipeline, daily is built from a read, a join and an aggregation. The code logs daily.count() and then writes daily with saveAsTable. Nothing is cached. What work does the cluster do?

    Sources431

    5.Lazy execution everywhere, lazy analysis only under Spark Connect

    DataFrame code runs in one of two deployments, and the difference decides when errors surface. Spark Connect is a gRPC-based protocol that specifies how a client application talks to a remote Spark server: the client builds the plan from your transformations and sends it, unresolved, to the server, which analyzes and runs it. Databricks uses Connect on serverless compute, with Databricks Connect, on standard compute for Python notebooks on Databricks Runtime 14.3 and above and Scala notebooks on 13.3 and above, and in Lakeflow pipelines with environment versions configured. Spark Classic is the mode that doesn't use Connect: DataFrame transformations are encoded in a logical plan, and analysis happens eagerly while that plan is built.

    Lazy *execution* and lazy *analysis* are separate ideas, and only lazy execution applies to every Spark deployment. In Spark Classic and in Spark Connect, transformations and spark.sql("select ...") queries are lazy, while actions such as collect() and show() run straight away. SQL commands like spark.sql("insert ...") and spark.sql("create ...") are an exception to watch for: they execute eagerly under both.

    Analysis timing is where the two differ. Spark Classic analyzes each plan eagerly as it is built and resolves every name immediately, so filtering on a column c that doesn't exist fails on that line, before any action. Spark Connect builds unresolved plans on the client and doesn't analyze them until something needs a resolved plan, such as schema access, explain, persisting or an action. Under Connect, the same bad filter only fails at df.columns or df.show(). The practical consequences are covered in Deferred analysis in Spark Connect.

    Execution and analysis timing in Spark Classic and Spark Connect
    AspectSpark ClassicSpark Connect
    Query executionLazyLazy
    Schema analysisEagerLazy
    Actions: df.collect(), df.show()Eager executionEager execution
    SQL commands: spark.sql("insert …"), spark.sql("create …")Eager executionEager execution

    Eager analysis in Classic doesn't mean any data is processed. Resolving column names checks the plan and runs no job, so even in Classic a misspelled column is caught without executing anything.

    Checkpoint 8 of 8· Match them up

    Match each line of code, and the deployment it runs on, to what happens when that line is reached.

    Tap a term, then the definition that fits it.

    Sources6

    Sources

    (8)

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

    1. 1.
      “Transformations: add some processing logic to the plan. Examples include reading data, joins, aggregations, and type casting.”
      ↩︎ Transformations build a plan, actions run it
      “none of the logic defined by a collection of operations are evaluated until an action is triggered”
      ↩︎ Transformations build a plan, actions run it
      “These optimizations consider all transformations triggered by a given action at once”
      ↩︎ Why waiting pays off: Catalyst optimizes the whole plan
      “Manually caching data or returning preview results in production pipelines can interrupt these optimizations and lead to increases in cost and latency.”
      ↩︎ Every action recomputes the plan
      “Transformations: add some processing logic to the plan. Examples include reading data, joins, aggregations, and type casting.”
      ↩︎ Exam trap 1
      “These optimizations consider all transformations triggered by a given action at once and find the optimal plan based on the physical layout of the data.”
      ↩︎ Checkpoint
    2. 2.
      “Because read is a transformation, Spark does not load data until you call an action such as display.”
      ↩︎ Transformations build a plan, actions run it
      “Some aggregations are actions, which means that they trigger computations.”
      ↩︎ Transformations build a plan, actions run it
    3. 3.
      “Lazy evaluation means that DataFrames store logical queries as a set of instructions against a data source rather than an in-memory result.”
      ↩︎ Transformations build a plan, actions run it
      “If you want to evaluate an intermediate step of your transformation, call an action.”
      ↩︎ Watching laziness line by line
      “Spark optimizes data processing by identifying the most efficient physical plan to evaluate logic specified by transformations.”
      ↩︎ Why waiting pays off: Catalyst optimizes the whole plan
      “In production data pipelines, writing data is typically the only action that should be present.”
      ↩︎ Every action recomputes the plan
      “All other actions interrupt query optimization and can lead to bottlenecks.”
      ↩︎ Every action recomputes the plan
      “Rather than evaluating each transformation in the exact order specified, Spark waits until an action triggers computation on all transformations.”
      ↩︎ Key concept
    4. 4.
      “RDDs support two types of operations: transformations, which create a new dataset from an existing one”
      ↩︎ Watching laziness line by line
      “This dataset is not loaded in memory or otherwise acted on: lines is merely a pointer to the file.”
      ↩︎ Watching laziness line by line
      “Reshuffle the data in the RDD randomly to create either more or fewer partitions and balance it across them.”
      ↩︎ Watching laziness line by line
      “return only the result of the reduce to the driver, rather than the larger mapped dataset”
      ↩︎ Why waiting pays off: Catalyst optimizes the whole plan
      “By default, each transformed RDD may be recomputed each time you run an action on it.”
      ↩︎ Every action recomputes the plan
      “By default, each transformed RDD may be recomputed each time you run an action on it.”
      ↩︎ Exam trap 3
    5. 5.
      “Provides the logical or physical plans for an input statement.”
      ↩︎ Watching laziness line by line
      “The optimized logical plan transforms through a set of optimization rules, resulting in the physical plan.”
      ↩︎ Why waiting pays off: Catalyst optimizes the whole plan
      “Provides the logical or physical plans for an input statement.”
      ↩︎ Exam trap 2
    6. 6.
      “Spark Classic performs analysis eagerly during logical plan construction.”
      ↩︎ Watching laziness line by line
      “Spark Connect is a gRPC-based protocol within Apache Spark that specifies how a client application can communicate with a remote Spark Server.”
      ↩︎ Lazy execution everywhere, lazy analysis only under Spark Connect
      “Transformations are constructed on the client side and sent as unresolved plans to the server.”
      ↩︎ Lazy execution everywhere, lazy analysis only under Spark Connect
      “Both Spark Classic and Spark Connect follow the same lazy execution model for query execution.”
      ↩︎ Lazy execution everywhere, lazy analysis only under Spark Connect
      “Spark Connect defers analysis and name resolution to execution time”
      ↩︎ Lazy execution everywhere, lazy analysis only under Spark Connect
      “spark.sql("select 1 as a, 2 as b").filter("c > 1") will not throw any error because the unresolved plan is client-side only”
      ↩︎ Lazy execution everywhere, lazy analysis only under Spark Connect
      “The key difference between Spark Connect and Spark Classic is that Spark Connect defers analysis and name resolution to execution time”
      ↩︎ Checkpoint
    7. 7.
      “The Apache Spark query optimizer (Catalyst) still plans your query”
      ↩︎ Why waiting pays off: Catalyst optimizes the whole plan
    8. 8.
      “Predicate pushdown is a performance optimization where the engine pushes your filter conditions to the storage layer.”
      ↩︎ Why waiting pays off: Catalyst optimizes the whole plan

    Ready to test yourself?

    Practise Databricks Certified Associate Developer for Apache Spark in quiz mode.

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