Sub topic 7
Silver: clean, type, and conform
This chapter covers the silver layer. It assumes you can read PySpark and SQL, know that bronze tables hold raw, append-only data with load metadata, and have a working idea of Delta tables and Unity Catalog names such as main.bronze.orders. Deduplication with MERGE and quality expectations each get their own chapter. Here you will see what silver is for and how to design it.
What silver is for
Bronze keeps data exactly as it arrived. That is useful for replay, but nobody wants to query it directly. Types are often strings, keys can be missing, and the same order can appear several times because a source system sent corrections.
Silver is the first layer built for consumption by other engineers. It holds data that is:
- Cleaned: invalid or unusable rows are removed or flagged.
- Typed: each column has the right data type, such as
TIMESTAMPorDECIMAL(12,2). - Conformed: names, units, codes, and keys follow one consistent convention, so tables from different sources can be joined.
- Deduplicated: there is one current row per business key.
Silver does not usually apply business-specific logic, such as "revenue per region per week". That belongs in gold. A good test is this: if two different gold tables would both want the same transformation, it belongs in silver.
Typing columns
Auto Loader with JSON often infers every field as a string, or leaves values as the source encoded them. Typing is the first job of silver. The typical casts are:
| Bronze value | Silver type | Notes |
|---|---|---|
| `"2026-11-30T10:15:00Z"` | `TIMESTAMP` | Know the source time zone. |
| `"19.90"` | `DECIMAL(12,2)` | Use decimals for money, not `DOUBLE`. |
| `"true"`, `"Y"` | `BOOLEAN` | Map codes explicitly. |
| `"00042"` | `STRING` | Keep identifiers with leading zeros as strings. |
A plain CAST returns NULL when a value cannot be converted, as long as ANSI mode is off. With ANSI mode on, which is the default on recent Databricks SQL warehouses and serverless compute, a bad cast raises an error and stops the job. Neither behavior is wrong, but you must know which one applies. Use TRY_CAST when you want a NULL for bad values and no failure, then handle the nulls on purpose.
SELECT
order_id,
TRY_CAST(order_ts AS TIMESTAMP) AS order_ts,
TRY_CAST(amount AS DECIMAL(12,2)) AS amount,
status
FROM main.bronze.ordersIf a cast fails, the row now has a NULL where bronze had a value. Keep the original bronze row reachable through the _source_file and _ingested_at columns, so you can investigate.
Cleaning rules
Cleaning means deciding what to do with each kind of problem. Common cases are:
- Missing keys. A row without
order_idcannot be matched or deduplicated. Drop it from silver, or send it to a quarantine table. - Whitespace and case. Trim strings and normalize case for fields used in joins, such as
lower(trim(email)). - Placeholder values. Convert strings such as
"N/A","null", or""to realNULL. - Out-of-range values. Negative amounts or dates in the year 1900 are often signs of upstream bugs.
- Schema drift. New columns that appear in bronze should be added to silver on purpose, not by accident.
Write these rules in one place, as a function or a view, so that every consumer of the data sees the same logic.
from pyspark.sql import functions as F
def clean_orders(df):
"""Type, trim, and filter raw bronze orders."""
blank_to_null = lambda c: F.when(F.trim(F.col(c)) == "", None).otherwise(F.trim(F.col(c)))
return (
df.select(
blank_to_null("order_id").alias("order_id"),
blank_to_null("customer_id").alias("customer_id"),
F.expr("try_cast(order_ts as timestamp)").alias("order_ts"),
F.expr("try_cast(amount as decimal(12,2))").alias("amount"),
F.lower(F.trim(F.col("status"))).alias("status"),
"_ingested_at",
"_source_file",
)
.where(F.col("order_id").isNotNull())
)
bronze = spark.read.table("main.bronze.orders")
clean_orders(bronze).createOrReplaceTempView("orders_clean")This reads bronze in batch for clarity. In a production flow you would read it as a stream, so only new rows are processed. The chapter on incremental processing explains that choice.
Conforming data
Conforming means that the same idea looks the same everywhere. If one source calls a customer cust_id and another calls it customerId, silver should expose one name, customer_id, with the same type and format in both tables.
Typical conforming steps:
- Rename columns to a house style, such as
snake_case. - Standardize codes. Map
"US","USA", and"United States"to a single value. - Standardize units and time zones. Store timestamps in UTC and amounts in one currency, or keep the currency in its own column.
- Align keys. Use the same key format across sources so that joins work.
Small code mappings can live in a lookup table in silver or a reference schema. Joining to a lookup table is easier to audit than a long CASE expression repeated in many notebooks.
Keep lineage columns
Keep _ingested_at and _source_file in silver, or at least a way to trace back to them. When a number looks wrong in a dashboard, these columns let you find the source file. Add a _processed_at column if you want to see when silver last touched a row.
Avoid carrying every bronze column forward without thought. Silver should expose a deliberate set of columns. Drop the ones nobody needs, and keep raw payloads in bronze, where they already live.
Nested and semi-structured data
JSON bronze data often contains nested structs and arrays. Silver usually flattens what consumers need.
SELECT
order_id,
customer.id AS customer_id,
customer.address.country AS country_code,
explode(items) AS item
FROM main.bronze.orders_nestedBe careful with explode. It changes the grain of the table from one row per order to one row per order line. The grain is what one row represents. State it in the table comment, and consider two silver tables, orders and order_items, instead of one table with mixed grain.
Grain and keys
Decide the grain of each silver table before you write it. For main.silver.orders, the grain is one row per order_id. The deduplication step in the next chapter depends on that decision, because MERGE needs a key that uniquely identifies a row.
Document the key, the grain, and the source in the table comment:
COMMENT ON TABLE main.silver.orders IS
'One row per order_id. Latest version of each order. Source: main.bronze.orders.';Full refresh versus incremental
There are two ways to build silver.
- Full refresh: rebuild the table from all of bronze each run. It is simple, and it fixes old mistakes automatically. It becomes slow and costly as bronze grows.
- Incremental: process only rows that arrived since the last run, then upsert them. It scales, but a rule change does not fix rows already processed unless you reprocess them.
Because bronze is replayable, you can always correct silver. If you fix a cleaning rule, rebuild silver from bronze. This is one of the main reasons to keep bronze raw. Plan for this from the start: write transformations so they are repeatable, with the same input always giving the same output.
Handling bad rows
Dropping rows silently hides problems. There are three common options:
| Approach | Behavior | Use when |
|---|---|---|
| Drop | Remove the row from silver. | The row is noise and a count is enough. |
| Quarantine | Write the row to a side table with a reason. | You need to inspect or repair rows later. |
| Fail | Stop the job. | Bad data means the source is broken. |
A quarantine table is often the best default for key problems. The data quality chapter returns to warn, drop, and fail behavior with expectations.
valid = F.col("order_id").isNotNull() & F.col("amount").isNotNull()
typed = clean_orders_no_filter(bronze) # same casts, without the final where()
typed.where(valid).write.mode("append").saveAsTable("main.silver.orders_staging")
(typed.where(~valid)
.withColumn("_reject_reason", F.lit("missing order_id or amount"))
.write.mode("append").saveAsTable("main.silver.orders_rejects"))Here clean_orders_no_filter stands for a version of clean_orders without its final where. Define it by splitting that function into a typing step and a filtering step.
Common mistakes
- Using
DOUBLEfor money. Floating-point rounding produces cents that do not add up. UseDECIMAL. - Ignoring time zones. A timestamp parsed in the wrong zone shifts orders to the wrong day, which then breaks daily gold totals.
- Casting without checking nulls. Count the
NULLs that casts create. A sudden jump means the source format changed. - Putting business aggregates in silver. This couples silver to one consumer and makes reuse harder.
- Dropping lineage columns. Without them, debugging means searching files by hand.
- Mixing grains. One table with both order rows and line rows leads to double-counted totals.
Summary
Silver turns raw bronze records into trusted, typed, consistent tables with a clear grain and key. You cast types deliberately, apply cleaning rules in one place, conform names and codes, keep lineage columns, and decide what happens to bad rows. Because bronze is replayable, silver can be rebuilt whenever a rule changes.
Exercise
A silver job casts amount with CAST(amount AS DECIMAL(12,2)). On Monday a source system starts sending "12,50" with a comma. On a cluster with ANSI mode off, what happens to those rows, and how would you make the problem visible instead of hidden?
Show answer
With ANSI mode off, the cast returns NULL for the comma values, so the rows reach silver with a missing amount and no error. To make it visible, use TRY_CAST on purpose, then route rows where the raw value is not null but the cast result is null into a quarantine table with a reject reason, and monitor the count of such rows. With ANSI mode on, the job would fail instead, which is also visible but stops the pipeline.
Exercise
You build one silver table from nested order JSON and use explode(items). Your gold daily revenue total doubles. What went wrong, and what is a better design?
Show answer
Exploding the items array changed the grain from one row per order to one row per order line. The order-level amount is repeated on every line, so summing it counts it several times. A better design is two silver tables: orders with one row per orderid, and `orderitems` with one row per order line, each with a documented key.