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.
| Operation listed for silver | Covered on this page? |
|---|---|
| Handling of null and missing values | Yes: dropna, fillna, replace, coalesce |
| Type casting | Yes: cast, try_cast, ANSI mode |
| Data deduplication | No, see lesson 3.4 |
| Data quality checks and enforcement | Only the link to constraints and quarantine, see lesson 3.7 |
| Joins | No, 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?
Silver should read from bronze (or silver) tables, never from the ingestion stream, because schema changes or corrupt records at the source would then cause failures in the silver pipeline. Because bronze grows by append, most reads from it should be streaming reads. Batch reads are for small datasets such as dimension tables.
“If you write directly from ingestion, you'll introduce failures due to schema changes or corrupt records in data sources.”Source: docs.databricks.com
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.
| Parameter | Default | Effect |
|---|---|---|
| how | 'any' | 'any' drops a row if it has any null; 'all' drops a row only if every value is null |
| thresh | None | Drops rows with fewer than thresh non-null values; when set, it overrides how |
| subset | None (all columns) | Limits the null check to the listed column names |
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.
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|
# +---+------+-----+thresh drops rows with fewer than thresh non-null values, and NaN counts as missing. Alice has 3, Bob has 2, Tom has 1 and the last row has 0, so thresh=2 keeps only Alice and Bob. thresh=1 would also keep Tom, and thresh=3 would keep only Alice.
Source: docs.databricks.comCheckpoint 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?
Correct answer: A — Call df.na.drop(subset=["order_total"]) so only rows missing the parsed total are dropped, leaving guest email nulls untouched
- A. Scoping
subsettoorder_totaldrops exactly the rows broken by the parsing bug while leaving every other column's nulls, including valid guest emails, intact. This targeted drop matches the requirement that only genuinely bad rows are removed. - B. The default
how='any'behavior evaluates every column, so it would also discard legitimate guest-checkout rows just becauseemailis null. That erases valid data the silver table is supposed to keep. - C. Filling the parsing-bug rows with a placeholder total masks corrupted data instead of removing it, which lets a fabricated zero-dollar order total flow into downstream aggregates as if it were real.
- D. Deduplicating on
order_totaladdresses repeated rows, not missing values, and it also risks collapsing distinct valid orders that happen to share a null total into a single row.
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?
Correct answer: A — Call df.na.drop(thresh=3) to keep only rows with at least three non-null values across their columns
- A. The
threshparameter counts non-null values per row and keeps only rows that meet or exceed that count, which directly implements the "at least 3 of 5 populated" rule described in the scenario. - B.
how="all"only drops a row when every column is null, so rows with just one populated metric out of five would still be kept, failing the minimum-threshold requirement. - C. Filtering on a single named column ignores the other four metrics entirely, so a row could pass with only
metric_1populated even though the rule requires at least three populated fields. - D. Filling every missing value with zero keeps sparse rows in the table by fabricating readings, which hides the exact rows the threshold rule is meant to discard.
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.
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"])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:
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?
fillna skips any column in subset whose type does not match the fill value, and it raises no error. The string column keeps its nulls. To fill it, cast quantity to a numeric type first, or pass a string value.
“Columns specified in subset that do not have matching data types are ignored.”Source: docs.databricks.com
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?
Correct answer: A — Use COALESCE(shipping_country, billing_country) so the billing value fills in only when shipping is missing
- A.
COALESCEreturns its first non-null argument, so it keeps the existingshipping_countrywhen present and substitutesbilling_countryonly for the null rows, matching the described fallback rule exactly. - B.
NULLIFreturns null when the two arguments are equal and otherwise returns the first argument, which does the opposite of filling a null and can never introduce thebilling_countryvalue. - C. Casting to
STRINGonly changes the declared type of the column and performs no null substitution, so any missingshipping_countryvalues remain null after this expression runs. - D. String concatenation with
||combines both columns into one text value, which corrupts populated rows and also yields null whenever either operand is null in most engines.
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.
> 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);
NULLChoose 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.
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|
# +----+Compare the result with the original string. A row where the raw value IS NOT NULL but the try_cast result IS NULL had a value that would not parse. A row where both are null was simply missing. Send the first kind to quarantine. The second kind goes through your normal null-handling rule.
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))Column.cast takes a DataType or a type name and converts the column to that type, usually inside withColumn. alias and withColumnRenamed only change the name. fillna replaces nulls and leaves the type unchanged.
Source: docs.databricks.com5.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.
| mode | Behaviour |
|---|---|
| '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.
If the target table already exists, the mode decides what saveAsTable does. The default, 'error'/'errorifexists', throws an exception. 'append' adds rows using the table's existing format and options. 'overwrite' replaces the contents, and the DataFrame schema doesn't have to match. 'ignore' makes no change.
“If the table already exists, the behavior depends on the mode parameter (default is to throw an exception).”Source: docs.databricks.com
Sources
(11)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 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.https://docs.databricks.com/aws/en/pyspark/basicsOfficial docs
“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.
“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.
“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.
“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.
“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.
“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.
“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.
“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.https://docs.databricks.com/aws/en/pyspark/reference/classes/dataframewriter/saveAsTableOfficial docs
“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.
“Spark checks for and rejects invalid casts, throwing an exception to ensure data quality.”
↩︎ Writing the cleaned result to a silver table