Published · By Henry Palma
Databricks Data Engineer Associate Exam Prep, Lesson 7: Bronze to Silver Cleaning with PySpark
Databricks Data Engineer Associate exam prep: clean a bronze table into silver with PySpark. Nulls, try_cast vs cast, split, rename, drop and filter.
Exam-style question: on serverless compute, a bronze table stores amount as a string, and one row holds N/A. You cast the column to DECIMAL(10,2) and write a silver table. What happens? The query fails with a CASTINVALIDINPUT error. Serverless compute runs with American National Standards Institute (ANSI) SQL mode on by default, so an invalid cast raises an error instead of quietly returning NULL. Use try_cast when you want bad values to become NULL. This post follows Lesson 7 of the Databricks Data Engineer Associate exam prep series, in Section 3 of the August 2026 exam guide, Data Transformation and Modeling (22% of the exam).

The notebook and cheat sheet are in the A07 folder on GitHub. The PDF cheat sheet is in the same folder. This is independent study material, not official Databricks training.
The exam objectives
Section 3 of the exam guide has two objectives this lesson covers:
- Implement data cleaning by reading bronze tables with PySpark or SQL, cleaning nulls, standardizing data types, and writing to new silver tables.
- Manipulate columns, rows and table structures by adding, dropping, splitting and renaming columns and applying filters. Exploding arrays, the last part of that objective, was Lesson 5.
Everything here runs in Databricks Free Edition, in a Python notebook on serverless compute with Unity Catalog. The outputs in this post were checked with a local Apache Spark 4.0 run of the same code, not on Databricks. Spark 4.0 also has ANSI mode on by default, so the cast error matches.
What bronze and silver mean
Databricks describes the medallion architecture as layers of data quality: bronze is raw, silver is validated, and gold is enriched for business use. Bronze keeps the source as it arrived, and Databricks recommends storing most bronze fields as strings so an unexpected value never drops a record. Silver is where you clean: handle nulls and missing values, cast types, enforce the schema, deduplicate, and run quality checks. You build silver by reading from bronze and writing a new silver table, not by cleaning in place.
Lessons 2 to 6 were about getting data into bronze. This lesson takes it one layer further.
The bronze table
The notebook creates a new schema in the workspace catalog (btsilver plus 12 random hex characters) and writes a small bronze table, bronze_orders, with every column as a string. Six fictional orders:
| orderid | customername | amount | orderdate | citystate | rescueddata | |---|---|---|---|---|---| | 1001 | " Ana Lopez " | 25.50 | 2026-11-02 | Austin, TX | null | | 1002 | Ben Wu | N/A | 2026-11-03 | Dallas, TX | null | | 1003 | null | 14.00 | 2026-11-03 | Denver, CO | null | | null | Cara Diaz | 9.99 | 2026-11-04 | Austin, TX | null | | 1005 | Dev Shah | null | 2026-11-05 | Tulsa, OK | null | | 1006 | Eli Park | 42.00 | 2026-11-05 | Austin, TX | null |
Each row has one problem to fix: extra spaces around Ana's name, N/A in Ben's amount, a missing customer on 1003, a missing orderid, a missing amount on 1005, and a combined citystate column. The rescueddata column is the kind of metadata column Auto Loader adds (Lesson 4). Here it is empty on every row.
import uuid
schema = "bt_silver_" + uuid.uuid4().hex[:12]
spark.sql(f"CREATE SCHEMA IF NOT EXISTS workspace.{schema}")
spark.sql(f"USE workspace.{schema}")
bronze = spark.read.table("bronze_orders") bronze.count() # 6 ```
Trap 1: cast fails on serverless, try_cast returns NULL
The obvious way to type amount is cast:
from pyspark.sql import functions as F
bronze.select(F.col("amount").cast("decimal(10,2)")).show()
# [CAST_INVALID_INPUT] The value 'N/A' of the type "STRING"
# cannot be cast to "DECIMAL(10,2)" because it is malformed.
The whole query fails because of one value. Databricks documents that serverless compute has ANSI mode enabled by default: invalid casts, arithmetic overflow and malformed input raise runtime errors instead of silently returning NULL. ANSI mode is also on by default in Apache Spark 4.0 and Databricks Runtime 17.0 and above. On classic compute with older runtimes, the same cast returned NULL without complaint, which is why code that worked on a classic cluster can fail when it moves to serverless.
try_cast is the tolerant version. If a value is malformed or does not fit the target type, it returns NULL instead of an error:
typed = bronze.withColumn(
"amount", F.expr("try_cast(amount AS DECIMAL(10,2))"))
Now 1002 has a NULL amount and the job keeps going. Two things to remember. trycast only forgives bad values, not impossible casts: if the source and target types are not a valid cast combination, you still get an error. And a NULL from trycast hides the original value, so count the bad rows before you filter them out:
bad = bronze.filter(
F.col("amount").isNotNull()
& F.expr("try_cast(amount AS DECIMAL(10,2))").isNull())
bad.count() # 1, order 1002 with N/A
Databricks' medallion example quarantines invalid records in the silver layer. Writing bad to its own table is one way to do that. Data quality checks and validation rules get a full lesson in A11.
Trap 2: dropna() with no subset drops everything
dropna() with no arguments uses how="any": it drops a row if any column is null. Every row here has a null rescueddata, so this returns zero rows:
bronze.dropna().count() # 0
bronze.dropna(subset=["order_id"]).count() # 5
Name the columns that must not be null with subset. how="all" drops a row only when every column is null, and thresh keeps rows with at least that many non-null values.
Trap 3: fillna only fills matching types
fillna(0) fills nulls in numeric columns only. A string column is ignored, so this leaves 1003's customer as NULL. The PySpark docs say columns that do not match the value's type are simply ignored. Use a dict to say exactly which column gets which value:
bronze.fillna(0) # customer_name still NULL
bronze.fillna({"customer_name": "unknown"})
The full bronze to silver pipeline
Here is the whole cleaning step in one chain. Each line maps to a verb in the exam objective:
silver = (bronze
.dropna(subset=["order_id"]) # nulls: drop rows
.withColumn("order_id", F.col("order_id").cast("int"))
.withColumn("amount",
F.expr("try_cast(amount AS DECIMAL(10,2))")) # types
.withColumn("order_date", F.to_date("order_date", "yyyy-MM-dd"))
.withColumn("customer_name", F.trim("customer_name"))
.fillna({"customer_name": "unknown"}) # nulls: fill
.withColumn("city", F.split("city_state", ", ").getItem(0)) # split, add
.withColumn("state", F.split("city_state", ", ").getItem(1))
.drop("city_state", "_rescued_data") # drop
.withColumnRenamed("customer_name", "customer") # rename
.filter(F.col("amount").isNotNull())) # filter
silver.write.mode("overwrite").saveAsTable("silver_orders") ```
The result is a managed Delta table in Unity Catalog with three rows:
| orderid | customer | amount | orderdate | city | state | |---|---|---|---|---|---| | 1001 | Ana Lopez | 25.50 | 2026-11-02 | Austin | TX | | 1003 | unknown | 14.00 | 2026-11-03 | Denver | CO | | 1006 | Eli Park | 42.00 | 2026-11-05 | Austin | TX |
The schema is typed now: orderid int, amount decimal(10,2), orderdate date, and the rest strings. Six bronze rows became three silver rows: the missing order_id was dropped first, then 1002 (N/A) and 1005 (missing amount) failed the amount filter.
A few details the exam likes:
withColumnadds a column, or replaces it if the name already exists. That is how the casts overwriteorderid,amountandorderdatein place.splittakes a regular expression pattern and returns an array.getItem(0)picks the first element. With ANSI mode on, an index past the end of the array raises an error. Databricks suggests theget()function, which returns NULL instead.dropandwithColumnRenameddo nothing if the column does not exist. A typo will not fail, it just leaves the column alone, so checksilver.columnsafter the chain.filterandwhereare the same thing.
The same silver table in SQL
The objective says PySpark or SQL. Here is the SQL version, a CREATE TABLE AS SELECT (CTAS) statement with the same rules:
CREATE OR REPLACE TABLE silver_orders AS
SELECT CAST(order_id AS INT) AS order_id,
coalesce(trim(customer_name), 'unknown') AS customer,
try_cast(amount AS DECIMAL(10,2)) AS amount,
to_date(order_date) AS order_date,
split(city_state, ', ')[0] AS city,
split(city_state, ', ')[1] AS state
FROM bronze_orders
WHERE order_id IS NOT NULL
AND try_cast(amount AS DECIMAL(10,2)) IS NOT NULL;
It returns the same three rows. In SQL, coalesce plays the role of fillna, and leaving a column out of the SELECT plays the role of drop.
For a slower walk through select, filter and nulls outside the exam series, see PySpark Data Cleaning on Databricks.
Practice challenge
Add a status column to the bronze table with the values "shipped", "SHIPPED", " Shipped" and null. In the silver table, make every value lowercase with no spaces, and fill nulls with "unknown".
Answer: chain .withColumn("status", F.lower(F.trim("status"))) and then add "status": "unknown" to the fillna dict. Trim and lowercase first, because both return NULL for a NULL input, and fillna then fills it.
Key takeaways
- Bronze keeps raw strings. Silver is a new table you write after cleaning nulls, casting types and filtering.
- Serverless compute has ANSI mode on:
castfails on a bad value,try_castreturns NULL. Count the NULLs it creates. dropna()with no subset drops a row if any column is null. Usesubset.fillnaonly fills columns that match the value's type. Use a dict.- Memory trick: cast fails loud, try_cast fails quiet. A quiet NULL still needs a count.
Next lesson (Lesson 8): joins and unions, including broadcast and cross joins.
Check your understanding
1. On serverless compute, you cast a string column holding N/A to DECIMAL(10,2). What happens?
- A)
N/Abecomes NULL - B)
N/Abecomes 0 - C) The query fails with a
CASTINVALIDINPUTerror - D) The row is dropped
2. Every row has a null rescueddata. What does bronze.dropna() return?
- A) All six rows
- B) Five rows
- C) Three rows
- D) Zero rows
3. What does fillna(0) do to a null in a string column?
- A) Fills it with "0"
- B) Leaves it NULL, because the column type does not match
- C) Raises an error
- D) Drops the row
4. You run withColumnRenamed("custname", "customer"), but the column is called customername. What happens?
- A) An error is raised
- B) A new empty
customercolumn is added - C) Nothing changes, because renaming a missing column is a no-op
- D)
customer_nameis renamed anyway
5. Where does Databricks recommend doing data cleaning and type casting?
- A) In the bronze layer, as data is ingested
- B) In the silver layer, by reading bronze and writing new silver tables
- C) In the gold layer, inside materialized views
- D) In the source system before ingestion
Answer key
- C. ANSI mode is on by default on serverless, so a malformed cast raises an error.
try_castwould return NULL. - D. With no subset,
dropnauseshow="any", and every row has a null inrescueddata. - B.
fillnaignores columns whose type does not match the fill value. Use a dict like{"customer_name": "unknown"}. - C.
withColumnRenamedis a no-op if the schema does not contain the column, so checkcolumnsafterward. - B. Bronze keeps raw data with minimal validation. Silver is where cleaning, type casting and quality checks happen.