3: Data Transformation and Modeling

    Data Cleaning from Bronze to Silver with PySpark and SQL

    Key points

    Bronze tables are the raw, append-only landing zone for ingested data. They hold every record exactly as it arrived plus a small set of metadata columns (ingest timestamp, source file path, batch id). A bronze table preserves history without judgment: malformed rows, duplicate records, and inconsistent types all coexist there because the bronze layer's only contract is "we captured what arrived."

    The silver layer breaks that pattern. Silver tables are the typed, cleaned, conformed contract every downstream consumer relies on. Every gold view, every dashboard, every machine learning feature ultimately reads from silver, so the silver pass is where the entire pipeline's correctness is decided.

    A silver transformation reads a bronze table, applies a deterministic set of cleansing rules, and writes the result back to a Delta table under the silver schema. The transformation is idempotent: rerunning it on the same bronze input produces the same silver output. Idempotency matters because Lakeflow Jobs retry failed tasks and Auto Loader checkpoints can replay records; without idempotency, retries create duplicates and drift away from the source of truth.

    Reading Bronze Tables

    PySpark exposes three equivalent ways to read a Unity Catalog table: spark.table("catalog.schema.table"), spark.read.table("catalog.schema.table"), and spark.sql("SELECT * FROM catalog.schema.table"). All three return a DataFrame backed by the same Delta scan plan; the choice of style is a readability decision rather than a performance one. SQL transformations execute through spark.sql() or run inline in a SQL notebook cell; the optimizer treats both paths identically.

    from pyspark.sql import functions as F
    
    bronze_df = spark.table("prod.bronze.customers")
    
    bronze_sql = spark.sql("""
     SELECT *
     FROM prod.bronze.customers
     WHERE ingest_ts >= current_date() - INTERVAL 1 DAY
    """)
    

    Reading a bronze table is rarely a SELECT *. The silver job typically restricts to the new arrivals since the last successful run; the watermark is held in a control table, in the Lakeflow Jobs parameter store, or implicitly through Structured Streaming checkpoints. For incremental silver pipelines, Change Data Feed on the bronze Delta table provides the row-level deltas without a full scan.

    Handling Nulls

    Nulls flow into bronze for predictable reasons: optional fields in source systems, schema evolution that added a column after the first load, malformed source rows where Auto Loader stored the original value in _rescued_data and left the typed column null.

    Silver code must make an explicit decision for every column:

    • drop the row,
    • fill with a default,
    • propagate the null forward,
    • or branch into a quarantine table.

    How it works

    PySpark provides three null-handling primitives.

    • df.na.drop() drops rows containing any null;
    • df.na.drop(subset=["customer_id"]) drops rows where the specified columns are null;
    • df.na.drop(how="all") drops only rows where every column is null. The df.dropna() alias is identical.

    For fills,

    • df.na.fill(0) replaces every null in numeric columns with zero,
    • df.na.fill({"region": "UNKNOWN", "tier": "STD"}) applies a column-specific dictionary,
    • F.coalesce(F.col("a"), F.col("b"), F.lit("DEFAULT")) returns the first non-null value among its arguments.
    cleaned = (
     bronze_df
     .na.drop(subset=["customer_id", "order_id"])
     .na.fill({"region": "UNKNOWN", "loyalty_tier": "STD"})
     .withColumn(
     "display_name",
     F.coalesce(F.col("preferred_name"), F.col("legal_name"), F.lit("Unknown"))
     )
    )
    

    In SQL, the analogues are COALESCE, NVL, IFNULL, and NULLIF. COALESCE accepts a list and returns the first non-null; NVL is the two-argument alias; IFNULL is the BigQuery-compatible spelling that Databricks accepts; NULLIF(a, b) returns null when a = b and otherwise returns a, which is the idiomatic way to convert a sentinel value (the literal string "N/A", the number -1) back into a real null.

    SELECT
     customer_id,
     COALESCE(preferred_name, legal_name, 'Unknown') AS display_name,
     NULLIF(region, 'N/A') AS region,
     NVL(loyalty_tier, 'STD') AS loyalty_tier
    FROM prod.bronze.customers
    WHERE customer_id IS NOT NULL;
    

    💡 Exam Trap: df.na.fill(0) only fills nulls in columns whose data type matches the fill value. Calling .fill(0) on a DataFrame with string columns leaves those string columns untouched even when they contain nulls. To fill string nulls, pass a string literal or a column-keyed dictionary.

    💡 Exam Trap: dropDuplicates(["customer_id"]) keeps an arbitrary row when duplicates exist; the choice is not deterministic across runs. To keep a specific row (the latest by ingest time), use row_number() windowed by the dedup key, ordered by the tiebreaker, and filter on rank one.

    Standardizing Data Types

    Bronze data arrives as strings far more often than schemas suggest.

    CSV files, JSON payloads, and REST responses serialize everything as text; Auto Loader and read_files infer types but route ambiguous values to _rescued_data.

    The silver pass converts string fields to their proper Spark types using cast() or, for safer conversions, try_cast() introduced for SQL and exposed as F.try_cast() in PySpark.

    • cast() raises an exception on conversion failure when invoked in strict ANSI mode and returns null in legacy mode; behavior depends on spark.sql.ansi.enabled.
    • try_cast() always returns null on failure, never throws, and pairs well with a null-handling rule downstream.
    • For dates and timestamps, to_date() and to_timestamp() accept an optional format string; mismatched formats land as null without exception.
    silver_typed = (
     cleaned
     .withColumn("customer_id", F.col("customer_id").cast("long"))
     .withColumn("signup_date", F.to_date("signup_date_str", "yyyy-MM-dd"))
     .withColumn("ltv_usd", F.try_cast(F.col("ltv_usd_str"), "decimal(18,2)"))
     .withColumn("email_lower", F.lower(F.trim(F.col("email"))))
    )
    
    SELECT
     CAST(customer_id AS BIGINT) AS customer_id,
     to_date(signup_date_str, 'yyyy-MM-dd') AS signup_date,
     try_cast(ltv_usd_str AS DECIMAL(18,2)) AS ltv_usd,
     LOWER(TRIM(email)) AS email_lower
    FROM prod.bronze.customers;
    
    • String standardization (lowercasing emails, trimming whitespace, removing zero-width characters) belongs in silver.
    • Numeric standardization (rounding currency to two decimals, converting units) also belongs there.
    • Timestamp zone normalization (storing everything as UTC and stamping the original zone in a sibling column) prevents downstream timezone bugs that are very hard to diagnose once dashboards have shipped.

    Writing to Silver Tables

    The write step has three common shapes.

    • A full overwrite replaces the entire silver table on each run; cheap for small dimension tables, prohibitively expensive for fact tables.
    • An append adds new rows without touching existing data; correct only when the bronze input never replays.
    • A MERGE INTO upsert matches on a key, updates existing rows, and inserts new ones; the standard pattern for fact and dimension silver tables fed by replayable bronze.
    (
     silver_typed
     .write
     .mode("overwrite")
     .option("overwriteSchema", "true")
     .saveAsTable("prod.silver.customers")
    )
    
    MERGE INTO prod.silver.customers AS t
    USING staging.customers_clean AS s
    ON t.customer_id = s.customer_id
    WHEN MATCHED AND s.updated_at > t.updated_at THEN
     UPDATE SET *
    WHEN NOT MATCHED THEN
     INSERT *;
    

    For streaming silver loads, foreachBatch wraps the merge inside a Structured Streaming query so that each micro-batch becomes a transactional upsert.

    The pattern works with Auto Loader bronze sources and provides exactly-once semantics when combined with Delta's idempotent writes.

    Lakeflow Spark Declarative Pipelines abstracts this behind APPLY CHANGES INTO, which is the preferred path when the silver table is defined inside a pipeline.

    ⚠️ Anti-Pattern: Writing silver with mode("append") from a bronze table that uses Change Data Feed without filtering on _change_type. The append captures the CDF metadata rows as well as the data rows, producing a silver table where every row appears multiple times under different change types. Always filter CDF reads to _change_type IN ('insert', 'update_postimage') before writing silver.

    📊 Limit: Delta MERGE INTO evaluates all matched conditions on every input row. With multiple WHEN MATCHED clauses, the first matching clause wins per row; the order in the SQL statement matters. There is no documented cap on the number of WHEN clauses, but each additional clause adds plan cost and complicates auditing.

    Decision Anchor: Cleaning Strategy

    Choose row-drop semantics when the missing field makes the record meaningless (a customer record without a customer_id, an order record without an order_id). Choose fill semantics when the missing field has a documented default the business agrees to (region defaults to UNKNOWN, loyalty tier defaults to STD).

    Choose quarantine semantics (route the bad row to a sidecar Delta table) when the row is suspect but the business needs an audit trail; this is the bronze-to-silver equivalent of expect_or_drop paired with a quarantine sink.

    🎯 Scenario: A retail bronze table receives nightly order extracts from three regional ERPs. Region A sends amounts as decimals, region B sends them as strings with embedded currency symbols, region C occasionally sends nulls when an order has been voided. The silver job uses regexp_replace to strip currency symbols, try_cast to convert to decimal(18,2), filters out voided rows with WHERE status <> 'VOID', and merges into prod.silver.orders on (region, order_id). The voided rows land in prod.quarantine.orders_void for finance reconciliation. The merge is idempotent because the source key is stable and the watermark on ingest_ts advances only after a successful write.

    A repeatable silver layer is the single biggest quality investment a data engineer makes.

    Bronze can be messy and gold can be denormalized; silver carries the type contract, the null contract, and the deduplication contract that every other layer assumes.

    When silver is reliable, every downstream artifact (the dashboards, the ML features, the regulatory extracts) inherits that reliability for free.

    When silver is broken, every downstream artifact is broken, and the cleanup work compounds because every team has built around the broken contract. ---

    Continue with the interactive course

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