3: Data Transformation, Cleansing, and Quality

    Write efficient Spark SQL and PySpark code to apply advanced data transformations, including window functions, joins, and aggregations, to manipulate and analyze large Datasets.

    The Silver layer is where ingestion provenance meets business semantics, and the cost of that meeting is paid almost entirely in shuffle.

    How it works

    Three transformation families dominate the Silver bill:

    • window functions that re-partition a stream by an entity key to compute ordered analytics
    • joins that merge fact rows with dimension lookups across heterogeneous distributions
    • aggregations that collapse many input rows into a single output row per group

    Each family has an Adaptive Query Execution (AQE) optimization, a Photon acceleration profile, and a Delta layout decision that decides whether the resulting Silver table is cheap to query downstream. This section walks each family from the Catalyst plan upward into the runtime knobs you have to know cold for the exam, then ties them back to file-size targets and clustering keys for the Silver table that holds the result.

    Engineers at the Professional tier are expected to write the same logical transformation in three ways and predict the plan each one produces: a single Spark SQL query, an equivalent DataFrame pipeline in PySpark, and a Lakeflow Spark Declarative Pipelines @dlt.table decorator. Catalyst compiles all three to the same physical operators when the inputs are identical, so the discriminator is rarely raw performance. It is parameterization, testability via DataFrame.transform, and reusability across Bundle targets.

    The exam tests whether you spot when Catalyst cannot match the three formulations (typically when an SQL string interpolates a runtime parameter that the planner sees only as a literal, or when a Python UDF blocks pushdown).

    The default rule is to write business logic in Spark SQL inside a CTAS or @dlt.table decorator, and reserve PySpark for orchestration glue, parameterized transforms registered with df.transform(fn), and procedural cleanup steps that benefit from applyInPandas.

    Spark SQL plays best with Unity Catalog views, row filters, and column masks; PySpark plays best with pytest, assertDataFrameEqual, and assertSchemaEqual from pyspark.testing. Treating both as interchangeable misses the point: the exam rewards picking the API whose strengths match the lifecycle stage.

    Beyond the API choice, every transform must declare its execution context:

    • batch via spark.read.table against a static Silver source
    • streaming via spark.readStream.table against a Delta source with Change Data Feed enabled
    • a Lakeflow SDP STREAMING LIVE TABLE that handles both checkpoint and trigger management implicitly

    The exam stresses the practical implication: in batch mode, window functions can sort the entire dataset because the planner sees the full input cardinality, while in streaming mode the same OVER (PARTITION BY ...) window is illegal across micro-batches unless the partition key is also the watermarked key. Confusing the two is the most common scenario distractor in this section.

    Window functions: partition, order, and frame discipline

    Window functions are the single highest-value pattern in Silver: every time an analyst needs the latest event per entity, a running total per account, or a ranking among siblings under a parent dimension, the answer is a window.

    The mechanics are governed by three clauses inside OVER:

    • PARTITION BY (which keys are grouped together for the window)
    • ORDER BY (which sort order applies within each partition)
    • the frame specification (which row range is in scope for the calculation)

    Catalyst implements the operator as a Window physical node that requires a shuffle on the partition key and an in-partition sort on the order key. The shuffle output partitions default to spark.sql.shuffle.partitions (200 unless AQE coalesces), and when the partition key is high-cardinality the result fans out across all of them. When the partition key is low-cardinality, AQE collapses small post-shuffle partitions into chunks of spark.sql.adaptive.advisoryPartitionSizeInBytes (64 MB default).

    In practice

    The professional-grade discipline is to write the frame explicitly rather than rely on defaults, because default frame semantics differ between ranking functions and value functions. ROW_NUMBER, RANK, and DENSE_RANK use a RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW frame implicitly. Value functions like SUM, AVG, MIN, MAX, FIRST, LAST, and the lag/lead family default to the same range frame only when ORDER BY is present, otherwise to the entire partition. Mixing the two in a single query without an explicit frame is the canonical source of "the running total drifts when I add a column" bug reports.

    -- Silver fact: latest valid event per account, plus running spend
    CREATE OR REPLACE TABLE prod_silver.sales.account_running_spend
    AS
    WITH ranked AS (
     SELECT
     account_id,
     event_id,
     event_ts,
     amount_usd,
     ROW_NUMBER() OVER (
     PARTITION BY account_id
     ORDER BY event_ts DESC, event_id DESC
     ) AS rn_latest,
     SUM(amount_usd) OVER (
     PARTITION BY account_id
     ORDER BY event_ts
     ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
     ) AS running_spend_usd
     FROM prod_bronze.sales.account_events
     WHERE event_ts IS NOT NULL
     AND amount_usd >= 0
    )
    SELECT
     account_id,
     event_id,
     event_ts,
     amount_usd,
     running_spend_usd,
     CAST(rn_latest = 1 AS BOOLEAN) AS is_latest_event
    FROM ranked;
    

    The frame ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW reads only the rows preceding the current one (inclusive), which is the desired semantic for a running total.

    Using RANGE BETWEEN on the same query introduces ties when two events share the same event_ts: both rows would include each other in the running sum, doubling the value.

    The exam writes this distractor as a CTAS that emits the right column names but wrong cumulative values, and asks you to spot the frame mismatch.

    Skew in the partition key is the single largest performance pitfall.

    When one account_id has ten million events and the next has fifty, the Window operator concentrates the work for the heavy account on one task.

    AQE skew handling helps for joins but not for windows: spark.sql.adaptive.skewJoin.enabled only repartitions a skewed join side.

    For windows the remedy is salting. You add a low-cardinality salt column to the partition key, compute the window per salt, then re-aggregate.

    This works for associative aggregations (SUM, COUNT, MIN, MAX) but not for ranking, which must see the full ordering per entity.

    from pyspark.sql import functions as F
    
    def add_running_spend_salted(df, salt_buckets=8):
     return (
     df
     .withColumn("salt", (F.hash("account_id", F.col("event_ts").cast("long")) % salt_buckets).cast("int"))
     .withColumn(
     "partial_running_spend",
     F.sum("amount_usd").over(
     Window
     .partitionBy("account_id", "salt")
     .orderBy("event_ts")
     .rowsBetween(Window.unboundedPreceding, Window.currentRow)
     )
     )
     .withColumn(
     "running_spend_usd",
     F.sum("partial_running_spend").over(
     Window.partitionBy("account_id").orderBy("event_ts")
     )
     )
     .drop("salt", "partial_running_spend")
     )
    

    This composition is unusual because the second window is still keyed only on account_id, but each input row to that second window is already the partial sum within a salt bucket, so the volume per partition shrinks by salt_buckets.

    The exam rarely demands you to write the salt code from scratch, but it expects you to recognize "salt the partition key" as the right answer when a window stage is described as running for 95 percent of total job time on one task.

    Confusing this with spark.sql.adaptive.skewJoin.enabled is a common trap.

    💡 Exam Trap: A scenario describes a window that hangs on one task for hours while the other 199 finish in seconds. The wrong answer is "enable AQE skew handling"; AQE skew handling is a join-side feature only. The right answer is to salt the partition key for associative aggregations, or to repartition the input by a higher-cardinality composite key before the window operator runs.

    📊 Limit: Default spark.sql.shuffle.partitions is 200. AQE post-shuffle target is spark.sql.adaptive.advisoryPartitionSizeInBytes = 64 MB (set via spark.conf.set). AQE coalesces small partitions into the target size; it does not split large ones beyond the skew-join trigger of 5 times the median plus spark.sql.adaptive.skewJoin.skewedPartitionThresholdInBytes (256 MB default).

    ⚠️ Anti-Pattern: Writing a window that omits ORDER BY for a value aggregation expecting "per-entity total". The default frame becomes RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING, which is the entity total, not a running total. The reader sees the running-total column drift downward when the upstream insert order changes. Always specify ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW when you mean a running total.

    LAG and LEAD complete the window vocabulary.

    LAG(col, n, default) returns the value of col from n rows before the current row in the window's order, falling back to default when fewer than n prior rows exist.

    The default of default is NULL, which is the most common reason a session-stitching pipeline emits NULL in the first row of every session: the lag has no predecessor.

    LEAD mirrors this forward.

    Both are pure window functions and do not trigger an additional shuffle beyond the one already required by the window's PARTITION BY.

    🎯 Scenario: A Silver pipeline computes session-level metrics by lagging event_ts per user_id ordered by event_ts ascending. The downstream dashboard shows every user's first event as a NULL session duration. The team adds COALESCE(LAG(event_ts) OVER w, event_ts) to make the duration zero for the first event in each user's history. The deeper question is whether NULL is signal or noise; in this case the dashboard owner wants zero, so the fix is correct, and the team adds a _first_in_partition boolean column derived from LAG(event_ts) IS NULL to make the semantic explicit downstream.

    Joins: broadcast, sort-merge, and AQE-aware tuning

    Joins are governed by three physical strategies that the planner picks based on table size estimates and join condition shape:

    • broadcast hash join (BHJ)
    • sort-merge join (SMJ)
    • shuffle hash join (SHJ)

    BHJ broadcasts the smaller side to every executor and probes it in memory against the larger side; it requires the small side to fit in spark.sql.autoBroadcastJoinThreshold (10 MB default) when AQE is off, and into the runtime per-executor broadcast budget when AQE is on.

    SMJ sorts both sides on the join key and merges; it scales to arbitrary sizes and is the default for two large tables.

    SHJ partitions both sides by the join key and builds a hash table on the smaller side per partition; it is rarely picked by Catalyst unless explicitly hinted, because it is sensitive to skew and per-partition memory pressure. AQE changes the strategy mid-query.

    When the actual size of a shuffle output is below the broadcast threshold, AQE upgrades an SMJ to a BHJ during runtime; this is spark.sql.adaptive.localShuffleReader.enabled.

    AQE skew handling splits a skewed partition on one side into multiple smaller partitions and replicates the matching partition from the other side; this is spark.sql.adaptive.skewJoin.enabled with the trigger at five times the median partition size plus 256 MB.

    Both behaviors require AQE to be enabled, which it is by default in Databricks Runtime.

    # Silver fact join with explicit broadcast hint and skew handling
    from pyspark.sql import functions as F
    
    dim_account = spark.read.table("prod_silver.sales.dim_account")
    fact_orders = spark.read.table("prod_bronze.sales.orders_clean")
    
    # Hint broadcast when we know the dimension fits the executor budget
    joined = (
     fact_orders.alias("o")
     .join(F.broadcast(dim_account).alias("a"), "account_id", "left")
     .select(
     "o.order_id",
     "o.order_ts",
     "o.amount_usd",
     "a.account_segment",
     "a.account_region"
     )
    )
    
    (joined
     .write
     .mode("overwrite")
     .clusterBy("account_region", "order_ts")
     .saveAsTable("prod_silver.sales.fact_orders_enriched"))
    

    The hint is necessary when the dimension is materialized from a streaming source where Catalyst cannot estimate the size accurately, or when statistics are stale.

    Without the hint Catalyst picks SMJ, which shuffles the fact table on account_id.

    Shuffling a billion-row fact table on a high-cardinality key is the slowest pattern in this section.

    The exam tests whether you spot a join that should have been broadcast but was not, and the answer is always either to add F.broadcast(small) in PySpark or /*+ BROADCAST(small) */ in SQL.

    -- Equivalent Spark SQL with explicit hint and AQE confidence
    SELECT /*+ BROADCAST(a) */
     o.order_id,
     o.order_ts,
     o.amount_usd,
     a.account_segment,
     a.account_region
    FROM prod_bronze.sales.orders_clean o
    LEFT JOIN prod_silver.sales.dim_account a
     ON o.account_id = a.account_id;
    

    Key points

    When the small side genuinely does not fit in memory, the broadcast hint backfires: each executor tries to materialize the dimension, hits OOM, and the job dies on driver-side OutOfMemoryError: GC overhead or executor OOMKilled.

    The fix is to leave the hint off and let Catalyst pick SMJ, then verify AQE skew handling is enabled.

    The exam will describe a failed broadcast with the OOM symptom and ask for the remediation; the answer is to remove the hint, not to increase the broadcast threshold blindly.

    Skew on a join key is the second canonical issue. When one account_id is 30 percent of the fact, the corresponding shuffle partition is 30 percent of the data, and one task runs forever.

    AQE skew handling splits that partition on the fact side and replicates the matching account on the dimension side. The split is automatic when the partition exceeds the threshold; no code change is needed beyond verifying spark.sql.adaptive.skewJoin.enabled = true.

    The exam writes this as "one task runs for 4 hours while others finish in 2 minutes; the join key is heavily skewed; what setting handles this?". The answer is AQE skew join. Confusing this with the salt-the-window trick from the previous subsection is the trap.

    The flow shows why AQE is a runtime-only check: stats can be wrong, and the upgrade or skew split only applies after the first shuffle has emitted real partition sizes. This is also why disabling AQE for "predictability" is the wrong answer on the exam; disabling AQE forfeits the post-shuffle decisions and the resulting plan stays pessimal whenever stats lie.

    💡 Exam Trap: A team disables AQE to make plans "more predictable" and reports that their large join now takes three times longer. The right answer is not to enable broadcast hints everywhere; the right answer is to re-enable AQE so the planner can promote SMJ to BHJ at runtime and split skewed partitions. Predictability of the plan is not the same as predictability of the runtime.

    📊 Limit: spark.sql.autoBroadcastJoinThreshold default is 10 MB. AQE runtime broadcast threshold is spark.sql.adaptive.autoBroadcastJoinThreshold (default same as the static one). Skew partition trigger is spark.sql.adaptive.skewJoin.skewedPartitionFactor * median + skewedPartitionThresholdInBytes with defaults of 5 and 256 MB.

    Inner, left, and right outer joins behave as expected.

    Left semi joins (LEFT SEMI) return rows from the left that have a match on the right, without the right-side columns, and they pushdown like a filter. The exam loves to test whether you replace an IN (SELECT ...) pattern with a LEFT SEMI JOIN for clarity and performance, with the catch that IN becomes a broadcast-style anti-join only when the subquery is small.

    Left anti joins (LEFT ANTI) return rows from the left that have no match on the right. Replacing NOT IN with LEFT ANTI JOIN avoids the NULL-handling bug where NOT IN returns nothing if any right-side value is NULL. The exam writes this as a query that mysteriously returns zero rows after a refactor; the fix is to replace NOT IN with LEFT ANTI JOIN.

    ⚠️ Anti-Pattern: Using NOT IN against a column that can be NULL on the right side. SQL three-valued logic makes the entire predicate UNKNOWN for any row when a NULL exists in the right-side set, and the result is an empty output. The remedy is LEFT ANTI JOIN or NOT EXISTS, which both handle NULLs correctly.

    Aggregations: groupings, approximate counts, and the rollup family

    Aggregations are conceptually simpler than windows or joins but hide three pitfalls that show up at the Professional tier.

    The first is the choice between GROUP BY, ROLLUP, CUBE, and GROUPING SETS.

    • ROLLUP(a, b, c) emits subtotals along the hierarchy ((a,b,c), (a,b), (a), ()).
    • CUBE(a, b, c) emits all subsets.
    • GROUPING SETS lets you list any combination explicitly.

    When to use

    The exam tests recognition of the right tool:

    • when a dashboard needs hierarchical subtotals (region, country, city), use ROLLUP.
    • when it needs every cross-product (region by product, region by channel, product by channel), use CUBE.
    • when only specific groupings are required, use GROUPING SETS so you do not compute unused subtotals.
    -- Hierarchical subtotals for a sales report
    SELECT
     region,
     country,
     city,
     GROUPING(region) + GROUPING(country) + GROUPING(city) AS level,
     SUM(amount_usd) AS total_usd,
     COUNT(*) AS order_count
    FROM prod_silver.sales.fact_orders_enriched
    GROUP BY ROLLUP(region, country, city);
    

    GROUPING(col) returns 1 when the column is being aggregated (subtotal row) and 0 when it is a literal value.

    Summing the GROUPING calls gives the hierarchy depth, which dashboards use to pick the right format.

    The exam tests whether you can distinguish a NULL that means "no data for this combination" from a NULL that means "this is a subtotal row"; the answer is always GROUPING(col) = 1 for subtotals.

    The second pitfall is approximate functions.

    • APPROX_COUNT_DISTINCT(col, rsd) uses HyperLogLog with relative standard deviation rsd (default 0.05).
    • It is one to two orders of magnitude faster than COUNT(DISTINCT col) on large inputs because it does not require a shuffle on the distinct key.
    • It aggregates per partition into a sketch and combines sketches at the end.

    Using it on a Silver aggregation table feeding a BI dashboard is the right call when the dashboard tolerates a 5 percent error band.

    The trap is using it for compliance metrics where an exact count is required by audit; the exam tests whether you spot that APPROX_COUNT_DISTINCT is the wrong tool for a regulatory report on unique customers per quarter.

    📊 Limit: APPROX_COUNT_DISTINCT(col, 0.01) reaches one percent relative standard deviation, the lowest the function supports. Reducing rsd below 0.01 raises an error. Smaller rsd increases per-partition sketch size proportionally.

    The third pitfall is COUNT(*) versus COUNT(col).

    COUNT(*) counts all rows; COUNT(col) counts non-NULL rows for col.

    When the column is nullable and the dashboard reports "orders with valid amount", COUNT(amount_usd) is what the user wants; COUNT(*) overstates by the number of NULL rows.

    The exam writes this as a discrepancy report between two metrics that should match; the fix is almost always replacing COUNT(*) with COUNT(specific_col) or guarding with a WHERE col IS NOT NULL.

    # PySpark grouping sets via DataFrame API
    agg = (
     spark.table("prod_silver.sales.fact_orders_enriched")
     .groupBy("region", "country", "city")
     .agg(
     F.sum("amount_usd").alias("total_usd"),
     F.count(F.col("order_id")).alias("order_count"),
     F.approx_count_distinct("account_id", 0.02).alias("approx_unique_accounts")
     )
    )
    
    # For the equivalent of GROUPING SETS, use SQL via spark.sql or expr
    hier = spark.sql("""
     SELECT region, country, city,
     GROUPING_ID(region, country, city) AS gid,
     SUM(amount_usd) AS total_usd
     FROM prod_silver.sales.fact_orders_enriched
     GROUP BY GROUPING SETS ((region, country, city), (region, country), (region), ())
    """)
    

    GROUPING_ID(cols...) returns a bitmap of which columns are being aggregated. It is more compact than summing individual GROUPING(col) calls and is the production pattern when the hierarchy has more than three levels. The exam knows both spellings.

    Adaptive Query Execution end to end and Photon acceleration

    AQE is on by default, and the exam expects you to know each of its four runtime decisions:

    • dynamically coalescing shuffle partitions
    • dynamically switching join strategies
    • dynamically optimizing skewed joins
    • dynamically pruning local shuffle reads

    Each behavior maps to a Spark config you can toggle when an outlier query misbehaves, but the standard advice is to leave AQE enabled and use the query profile to confirm it took the right runtime path.

    The query profile UI shows the per-stage output partition count and whether AQE coalesced or split; when you see "200 partitions, 199 empty", AQE was disabled and you forfeited the coalesce step.

    Photon is the C plus plus vectorized engine that replaces the JVM execution path for supported operators.

    It accelerates joins, aggregations, and window functions when the inputs are Parquet or Delta and the predicates are pushdown-friendly.

    Photon falls back to the JVM for unsupported operators silently, so a Python UDF in the middle of a Photon-eligible query disables Photon for the entire stage.

    The exam writes this as "we added a UDF and the job slowed by 5x; why?" and the answer is that the UDF blocked Photon for the surrounding stage.

    The remedy is to express the logic as built-in functions, a Pandas UDF (which runs in vectorized Arrow batches and is less hostile to Photon than a row-at-a-time Python UDF), or a SQL function written in Python and registered via CREATE FUNCTION ... LANGUAGE PYTHON, which on Databricks SQL warehouses runs in a managed sandboxed environment compatible with Photon.

    💡 Exam Trap: A team rewrites a Spark SQL aggregation as a Python UDF for clarity. The job slows by an order of magnitude. The wrong answer is to add more workers; the right answer is to either return to built-in functions or rewrite the UDF as a Pandas UDF so the per-batch overhead is amortized across thousands of rows. Built-in functions are always the first choice because they preserve Photon and Catalyst pushdown.

    The Decision Anchor for this section is the API choice:

    • Choose Spark SQL inside CTAS or @dlt.table when the logic is declarative, the inputs are Unity Catalog tables, and the result must be reviewed by analysts who read SQL.
    • Choose PySpark with DataFrame.transform and assertDataFrameEqual when the logic is composed of reusable steps, parameterized across Bundle targets, and unit-tested in CI.
    • Choose a hybrid (SQL inside a Python file via spark.sql(...)) when business logic lives in SQL but orchestration must vary per environment.

    Testing transformations with assertDataFrameEqual

    The professional tier expects unit tests on every non-trivial transform. The pyspark.testing module provides assertDataFrameEqual(actual, expected, rtol=0, atol=0, checkRowOrder=False) and assertSchemaEqual(actual_schema, expected_schema). Both raise on mismatch with a diff payload, and both integrate with pytest. The pattern is to express the transform as a function that takes a DataFrame and returns a DataFrame, compose it with df.transform(fn) in production code, and call it directly in tests with a tiny synthetic input.

    # silver/transforms/running_spend.py
    from pyspark.sql import DataFrame, Window
    from pyspark.sql import functions as F
    
    def add_running_spend(df: DataFrame) -> DataFrame:
     w = Window.partitionBy("account_id").orderBy("event_ts").rowsBetween(Window.unboundedPreceding, Window.currentRow)
     return df.withColumn("running_spend_usd", F.sum("amount_usd").over(w))
    
    # tests/test_running_spend.py
    from pyspark.testing import assertDataFrameEqual
    from silver.transforms.running_spend import add_running_spend
    
    def test_running_spend_orders_by_event_ts(spark):
     input_df = spark.createDataFrame([
     ("a", 1, 10.0),
     ("a", 2, 20.0),
     ("a", 3, 30.0),
     ], "account_id string, event_ts int, amount_usd double")
    
     expected_df = spark.createDataFrame([
     ("a", 1, 10.0, 10.0),
     ("a", 2, 20.0, 30.0),
     ("a", 3, 30.0, 60.0),
     ], "account_id string, event_ts int, amount_usd double, running_spend_usd double")
    
     assertDataFrameEqual(add_running_spend(input_df), expected_df)
    

    The test runs in milliseconds on a local Spark session, gives a reproducible failure when the frame semantics change, and serves as the canonical example of every transform in the Silver project.

    The exam scenario writes this as "the team refactored the running-total query and the dashboard quietly regressed by two percent; what should they have done?"

    The answer is assertDataFrameEqual on a deterministic input, run in CI on every commit before the Bundle deploys to staging.

    🎯 Scenario: A junior engineer rewrites a join from SQL to PySpark and changes the join key from account_id to account_uuid (both columns exist in the dimension). The dashboard silently loses 12 percent of orders that have NULL account_uuid. The team adds an assertDataFrameEqual test that asserts the joined row count matches the input row count exactly when all input rows have a valid account_id. The next refactor catches the regression in CI before the Bundle promotes to production.

    Decision anchors for transform writing

    Choose Spark SQL inside CTAS or a @dlt.table SQL block when the transform is declarative, the inputs are Unity Catalog tables, and analysts must review the logic.

    Choose PySpark with DataFrame.transform when the transform is reusable, parameterized across Bundle targets, or unit-tested with assertDataFrameEqual.

    Choose a hybrid (SQL inside a Python module via spark.sql) only when both demands apply.

    • Choose broadcast hint when the small side is provably under the executor budget and Catalyst's estimate is wrong; otherwise let AQE upgrade SMJ to BHJ at runtime.
    • Choose salt-the-partition-key when a window stage stalls on one task; AQE skew handling does not help windows.
    • Choose APPROX_COUNT_DISTINCT for BI dashboards with a tolerated error band; choose COUNT(DISTINCT) for compliance and audit reports.

    Continue with the interactive course

    Track your progress, jump into practice questions and use the Shark AI tutor inside the Databricks - Data Engineer Professional learning hub.