CertSafari
    Databricks Certified Data Engineer Associate· Lessons

    Domain 3 · Lesson 10/33

    Cleaning bronze data into silver tables: nulls, types and writes

    Implement data cleaning by reading bronze tables with PySpark/SQL, cleaning nulls, standardizing data types, and writing to new silver tables

    19 min read
    3.14% of exam
    11 sources
    Published 22 Oct 2026
    Docs as of 17 Oct 2026

    What you will be able to do

    • Read a bronze table with PySpark or SQL as the input to a silver cleaning step
    • Choose between dropna with how, thresh and subset so that only genuinely unusable rows are removed
    • Fill nulls with fillna, coalesce or a CASE expression, and replace sentinel values such as -1 or empty strings
    • Cast raw string columns to real types and predict whether cast or try_cast errors or returns NULL under ANSI mode
    • Write the cleaned DataFrame to a new silver table with saveAsTable or INSERT INTO

    Key concept

    Silver-layer cleaning — Bronze keeps source data raw, mostly as strings, nulls included. The silver step reads that bronze table, decides which nulls are allowed and which are defects, casts columns to their real types, and writes the result to a separate silver table.

    1.What bronze hands to silver

    A bronze table is deliberately untidy, and cleaning starts from that fact. In the Medallion architecture (bronze, silver, gold), bronze holds raw ingested data with no cleanup, and silver is where it gets cleaned and validated. Bronze also keeps most fields as string, VARIANT or binary, so that an unexpected schema change upstream cannot cause data to be dropped. So a silver job usually gets three things from bronze: numbers and dates stored as text, nulls whose meaning depends on the column, and some rows that are broken.

    Silver always reads from a table. The source is one or more bronze or silver tables, never the ingestion stream itself. Writing to silver straight from ingestion means a schema change or corrupt record at the source becomes a failure in your silver pipeline. In PySpark you load a Unity Catalog table with spark.table('<catalog>.<schema>.<table>'). In SQL you select from it in an INSERT INTO silver_table SELECT ... FROM bronze_table statement. Bronze tables grow by append, so most reads from bronze should be streaming reads. Batch reads are for small datasets such as dimension tables.

    Silver-layer operations that this cleaning step performs, and where the others are taught
    Operation listed for silverCovered on this page?
    Handling of null and missing valuesYes: dropna, fillna, replace, coalesce
    Type castingYes: cast, try_cast, ANSI mode
    Data deduplicationNo, see lesson 3.4
    Data quality checks and enforcementOnly the link to constraints and quarantine, see lesson 3.7
    JoinsNo, see lesson 3.2

    Checkpoint 1 of 8· Check yourself

    A team wants its silver orders table to stay current with a Kafka feed. A colleague suggests skipping bronze and writing to silver straight from the Kafka stream to save a hop. What is the recommended design?

    Sources12

    2.Dropping rows with dropna: how, thresh and subset

    dropna returns a new DataFrame without the rows that contain null or NaN values. df.dropna(...) and df.na.drop(...) are aliases. Three parameters decide which rows count as unusable, and the default is the most aggressive setting.

    dropna parameters and their effect
    ParameterDefaultEffect
    how'any''any' drops a row if it has any null; 'all' drops a row only if every value is null
    threshNoneDrops rows with fewer than thresh non-null values; when set, it overrides how
    subsetNone (all columns)Limits the null check to the listed column names
    With no arguments, dropna keeps only Alice. Bob is dropped because a NaN height counts as missingpython
    df = spark.createDataFrame([
        Row(age=10, height=80.0, name="Alice"),
        Row(age=5, height=float("nan"), name="Bob"),
        Row(age=None, height=None, name="Tom"),
        Row(age=None, height=float("nan"), name=None),
    ])
    
    df.na.drop().show()
    # +---+------+-----+
    # |age|height| name|
    # +---+------+-----+
    # | 10|  80.0|Alice|
    # +---+------+-----+

    A bare na.drop() often deletes too much. Take an orders table where email is null for every guest checkout, and the null is expected. Here na.drop() deletes every guest order. If the defect you want to remove is a null order_total left by a parsing bug, name that column: df.na.drop(subset=["order_total"]). Only the rows missing the parsed total go, and guest rows with a null email stay. Filling order_total with 0 is a different decision. The bad row stays in the table with a total nobody ever recorded, and every sum computed from it includes that made-up zero.

    how='all' is the most permissive setting, not the strictest. It removes only rows that are completely empty. When a row is usable once enough of its fields are populated, use thresh, which counts non-null values. For a sensor table where a reading needs at least 3 of its 5 metrics, df.na.drop(thresh=3) drops every row with fewer than three non-null values. Add subset with the five metric columns so that ID and timestamp columns are not counted toward the 3. In the four-row example above, thresh=2 keeps Alice and Bob.

    thresh=2 keeps rows with at least two non-null valuespython
    df.na.drop(thresh=2).show()
    # +---+------+-----+
    # |age|height| name|
    # +---+------+-----+
    # | 10|  80.0|Alice|
    # |  5|   NaN|  Bob|
    # +---+------+-----+

    Dropping a row deletes it for good, and auditing it later means going back to bronze. Databricks' medallion example for a business operations team cleans its customer and transaction data in the silver layer by dropping nulls and quarantining invalid records, which means setting the bad rows aside in a separate table instead of discarding them. When a null key means something went wrong upstream, write those rows to a quarantine table rather than letting dropna discard them without trace. See Quarantining invalid records.

    Checkpoint 2 of 8· Fill the gap

    Take the four-row DataFrame from this section (Alice; Bob with a NaN height; Tom with only a name; a row with no values). Which thresh value gives exactly the output shown?

    df.na.drop(thresh= ? ).show()
    # +---+------+-----+
    # |age|height| name|
    # +---+------+-----+
    # | 10|  80.0|Alice|
    # |  5|   NaN|  Bob|
    # +---+------+-----+

    Checkpoint 3 of 8· Exam question

    A bronze orders table has nulls in email (expected for guest checkouts) and nulls in order_total (caused only by an upstream parsing bug). Which approach correctly cleans this bronze table into a silver table while keeping valid guest rows?

    Checkpoint 4 of 8· Exam question

    A data engineer is cleaning a bronze sensor_readings table where a valid row needs at least 3 of its 5 metric columns populated to be usable, and rows below that threshold should be discarded before writing to silver. Which call achieves this?

    Sources31

    3.Filling nulls and replacing sentinel values

    Fill a null when a default is a true statement about the record. A missing name can become 'unknown', and a missing account balance can become 0 if the business agrees that missing means zero. fillna (alias na.fill) takes one value for all type-compatible columns, or a dict that maps column names to replacement values. Replacement values must be int, float, boolean or string. When you pass a dict, subset is ignored.

    The fill examples on this page use this four-row DataFrame, with numeric age and height, a string name and a boolean bool columnpython
    df = spark.createDataFrame([
        (10, 80.5, "Alice", None),
        (5, None, "Bob", None),
        (None, None, "Tom", None),
        (None, None, None, True)],
        schema=["age", "height", "name", "bool"])
    A dict gives each column its own replacement. Columns not in the dict keep their nullspython
    df.na.fill({'age': 50, 'name': 'unknown'}).show()
    # +---+------+-------+----+
    # |age|height|   name|bool|
    # +---+------+-------+----+
    # | 10|  80.5|  Alice|NULL|
    # |  5|  NULL|    Bob|NULL|
    # | 50|  NULL|    Tom|NULL|
    # | 50|  NULL|unknown|true|
    # +---+------+-------+----+

    Data types matter here, and the failure gives no warning. Columns in subset whose type does not match the fill value are skipped without an error. On the DataFrame above, df.na.fill(50) fills the numeric age and height but leaves name and bool null. df.na.fill(False) changes only the boolean bool column, turning its nulls into false. If a fill seems to do nothing, check the column type against the value you passed.

    Some nulls arrive disguised as values. An upstream system that cannot encode NULL may write -1 or an empty string instead. Convert those to real nulls or labels in silver, so that downstream queries do not each need their own rule to skip them. na.replace swaps given values in chosen columns. For example, df_customer.na.replace([""], ["UNKNOWN"], subset=["c_phone"]) turns empty phone strings into UNKNOWN. In SQL, a CASE expression turns a sentinel back into NULL:

    Turning the -1 placeholder into a real NULL while copying bronze into silversql
    INSERT INTO silver_table
      SELECT
        * EXCEPT weight,
        CASE
          WHEN weight = -1 THEN NULL
          ELSE weight
        END AS weight
      FROM bronze_table;

    Use coalesce when the fallback comes from another column rather than a constant. coalesce(expr1, expr2, ...) returns its first non-null argument. It evaluates arguments from left to right and stops at the first non-null one. If every argument is NULL, it returns NULL. COALESCE(shipping_country, billing_country) keeps the shipping value when one is present and uses the billing country only when shipping is missing. All arguments must share a least common type, which is another reason to cast columns before you coalesce them. CAST changes a column's type and fills nothing. The || operator joins two strings together and fills nothing either.

    Checkpoint 5 of 8· Check yourself

    In a silver job, quantity is still the string column it was in bronze. An engineer runs df.na.fill(0, subset=["quantity"]) before casting it. What happens to the null quantities?

    Checkpoint 6 of 8· Exam question

    In Spark SQL, which expression fills a null shipping_country with the value from billing_country only when shipping_country is missing, and leaves it unchanged otherwise?

    Sources4256

    4.Casting string columns: cast, try_cast and ANSI mode

    Bronze columns are mostly strings, so silver has to turn '42' into an INT and '2024-01-05' into a DATE. In PySpark that is col("x").cast("int") or .cast(IntegerType()), usually inside withColumn. In SQL it is cast(x AS INT). The real question is what happens to a value that cannot be cast, such as 'a', and the answer depends on ANSI mode.

    ANSI mode makes cast strict. With ANSI_MODE = TRUE, the system default for Databricks SQL accounts created on or after October 19, 2022, a string that is not a valid number causes an error, and so does a numeric overflow. With ANSI mode off, cast('a' AS INTEGER) returns NULL and cast(12345 AS TINYINT) silently returns 57. In Databricks Runtime the same switch is spark.sql.ansi.enabled. try_cast behaves the same way in both modes. If the value is malformed or does not fit the target type, it returns NULL instead of raising an error.

    The same invalid input under ANSI mode: cast raises an error, try_cast returns NULLsql
    > SET ansi_mode = true;
    
    -- Protects against integral numeric overflow
    > SELECT cast(12345 AS TINYINT);
      Casting 12345 to tinyint causes overflow
    
    -- For invalid values raises errors instead of returning NULL.
    > SELECT cast('a' AS INTEGER);
      Invalid input syntax for type numeric: a.
      To return NULL instead, use 'try_cast'
    
    -- try_cast() is consistent for both modes
    > SELECT try_cast('a' AS INTEGER);
      NULL

    Choose between them by deciding what one bad value should do. Plain cast under ANSI mode stops the whole job at the first bad value. That suits a column that must never be malformed, where you want a loud failure. try_cast keeps the job running and marks each bad value as NULL. That suits messy source data, provided you then deal with those NULLs. try_cast only tolerates bad values: if the cast between the two types is not supported at all, it still returns a DATATYPE_MISMATCH error. Databricks recommends explicit cast or try_cast over relying on ANSI_MODE = FALSE, because non-ANSI behaviour is lenient and inconsistent. In PySpark, Column.try_cast is available from Databricks Runtime 15.0.

    PySpark try_cast: the unparseable 'Bob' and the original None both come out as NULLpython
    from pyspark.sql.types import LongType
    df = spark.createDataFrame(
         [(2, "123"), (5, "Bob"), (3, None)], ["age", "name"])
    df.select(df.name.try_cast(LongType())).show()
    
    # +----+
    # |name|
    # +----+
    # | 123|
    # |NULL|
    # |NULL|
    # +----+

    Checkpoint 7 of 8· Fill the gap

    A silver job must store the customer key c_custkey as a string, not an integer. Which Column method completes this line so the column's data type actually changes?

    from pyspark.sql.functions import col
    
    df_casted = df_customer.withColumn("c_custkey", col("c_custkey"). ? (StringType()))
    print(type(df_casted))

    Sources789

    5.Writing the cleaned result to a silver table

    The cleaned DataFrame goes into a new table, and bronze stays as it is so it can be reprocessed later. df.write.saveAsTable("catalog.silver.orders") creates the table. What happens when the table already exists depends on mode: the default raises an error. saveAsTable matches columns by name, unlike insertInto, so column order in the DataFrame does not matter. In SQL, INSERT INTO silver_table SELECT ... FROM bronze_table does the cleaning and the write in one statement.

    saveAsTable modes when the silver table already exists
    modeBehaviour
    'error' / 'errorifexists' (default)Throws an exception
    'append'Adds rows, using the existing table's format and options
    'overwrite'Replaces the contents; the DataFrame schema need not match the existing table
    'ignore'Leaves the existing table untouched

    The silver table's types protect the write even if you forget a cast. spark.sql.storeAssignmentPolicy defaults to ANSI. When a source value's type does not match the target column, Spark adds an ANSI cast to the INSERT. An invalid value then fails the insert, and nothing is partially written. Rows you separate out during cleaning, such as rows with null keys or values that failed try_cast, should go to their own table in a separate write operation. Databricks recommends always processing filtered data as a separate write operation, especially with Structured Streaming, because using .foreachBatch to write to multiple tables can lead to inconsistent results.

    After the first load, add table constraints that encode the cleaning rules, so that a later job cannot break them. Cleaning is applied once, but a constraint checks every future write. If silver must never hold a null order_id, add a NOT NULL constraint. This can only be enabled on an existing table when the column holds no nulls already, so run the cleaning first and add the constraint second. Range rules such as quantity >= 0 become CHECK constraints. See Delta table constraints (NOT NULL, CHECK, informational PK/FK).

    Checkpoint 8 of 8· Match them up

    Match each saveAsTable mode to what happens when the cleaned DataFrame is written to catalog.silver.orders, a silver table that already exists.

    Tap a term, then the definition that fits it.

    Sources10115

    Sources

    (11)

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

    1. 1.
      “Databricks recommends storing most fields as string, VARIANT, or binary to protect against unexpected schema changes.”
      ↩︎ What bronze hands to silver
      “To build the silver layer, read data from one or more bronze or silver tables, and write data to silver tables.”
      ↩︎ What bronze hands to silver
      “Assuming all sources are append-only, configure most reads from bronze as streaming reads.”
      ↩︎ What bronze hands to silver
      “Data about customers and transactions is cleaned by dropping nulls and quarantining invalid records.”
      ↩︎ Dropping rows with dropna: how, thresh and subset
      “Data cleanup and validation are performed in silver layer.”
      ↩︎ Key concept
      “If you write directly from ingestion, you'll introduce failures due to schema changes or corrupt records in data sources.”
      ↩︎ Checkpoint
    2. 2.
      “To create a DataFrame from a table in Unity Catalog, use the table method”
      ↩︎ What bronze hands to silver
      “To replace strings with other values, use the replace method.”
      ↩︎ Filling nulls and replacing sentinel values
    3. 3.
      “Returns a new DataFrame omitting rows with null or NaN values.”
      ↩︎ Dropping rows with dropna: how, thresh and subset
      “If 'any', drop a row if it contains any nulls.”
      ↩︎ Exam trap 1
      “If specified, drop rows that have less than thresh non-null values. This overwrites the how parameter.”
      ↩︎ Exam trap 2
      “If 'all', drop a row only if all its values are null.”
      ↩︎ Prediction
    4. 4.
      “If the value is a dict, then subset is ignored and value must be a mapping from column name (string) to replacement value.”
      ↩︎ Filling nulls and replacing sentinel values
      “Columns specified in subset that do not have matching data types are ignored.”
      ↩︎ Exam trap 3
      “Columns specified in subset that do not have matching data types are ignored.”
      ↩︎ Checkpoint
    5. 5.
      “the placeholder value -1 is used to represent missing data.”
      ↩︎ Filling nulls and replacing sentinel values
      “Databricks recommends always processing filtered data as a separate write operation, especially when using Structured Streaming.”
      ↩︎ Writing the cleaned result to a silver table
      “Using .foreachBatch to write to multiple tables can lead to inconsistent results.”
      ↩︎ Writing the cleaned result to a silver table
      “It can only be enabled on an existing table if no existing records in the column are null”
      ↩︎ Writing the cleaned result to a silver table
    6. 6.
      “coalesce evaluates arguments left to right until a non-null value is found. If all arguments are NULL, the result is NULL.”
      ↩︎ Filling nulls and replacing sentinel values
    7. 7.
      “For accounts created on or after October 19, 2022, the system default is TRUE.”
      ↩︎ Casting string columns: cast, try_cast and ANSI mode
      “Databricks recommends using the explicit cast or try_cast function instead of relying on ANSI_MODE = FALSE.”
      ↩︎ Casting string columns: cast, try_cast and ANSI mode
      “For each of these casts you can use try_cast instead of cast to return NULL rather than of an error.”
      ↩︎ Exam trap 4
      “For invalid values raises errors instead of returning NULL.”
      ↩︎ Prediction
    8. 8.
      “If the source and target types are not a valid cast combination, a DATATYPE_MISMATCH error is returned.”
      ↩︎ Casting string columns: cast, try_cast and ANSI mode
    9. 9.
      “Try to convert the column to a different data type. Returns null if conversion fails.”
      ↩︎ Casting string columns: cast, try_cast and ANSI mode
    10. 10.
      “Unlike DataFrameWriter.insertInto, DataFrameWriter.saveAsTable uses column names to find the correct column positions.”
      ↩︎ Writing the cleaned result to a silver table
      “If the table already exists, the behavior depends on the mode parameter (default is to throw an exception).”
      ↩︎ Checkpoint
    11. 11.
      “Spark checks for and rejects invalid casts, throwing an exception to ensure data quality.”
      ↩︎ Writing the cleaned result to a silver table

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