Sub topic 13
Organizing data with the medallion pattern
This chapter assumes you can read basic SQL and PySpark, you know what a Delta table is, and you understand the Unity Catalog three-level name (catalog.schema.table) from earlier chapters. It covers the medallion pattern: what the bronze, silver, and gold layers are, how to build them, and where they commonly go wrong.
What the medallion pattern is
The medallion pattern is a way to organize tables in a lakehouse into layers. Each layer holds data that is more refined than the one before it. Data moves forward through the layers, and each step adds structure or quality.
The pattern is a convention, not a feature of Databricks. Nothing in the platform forces you to use it. It works well because Delta Lake gives you reliable tables at every layer, and Unity Catalog lets you control access to each layer separately.
| Layer | Contents | Typical users | Typical operations |
|---|---|---|---|
| Bronze | Raw data as received, with load metadata added | Data engineers | Append, ingest, retain history |
| Silver | Cleaned, deduplicated, validated, conformed records | Engineers, analysts, data scientists | Cast types, filter, deduplicate, join |
| Gold | Business-level tables built for a specific use | Analysts, dashboards, ML features | Aggregate, model, publish |
Why use layers
Separating raw data from cleaned data solves several practical problems.
- Reprocessing. If your cleaning logic has a bug, you can fix it and rebuild silver from bronze. Without a raw copy, you would have to go back to the source, which may no longer hold the old data.
- Auditing. Bronze shows what you actually received, including bad records.
- Separation of concerns. Ingestion code only needs to land data. Cleaning code only needs to fix it. Business logic lives in gold.
- Access control. You can give analysts access to gold only, and keep raw data with personal information restricted to a small group.
- Reuse. Several gold tables can share one silver table, so cleaning rules exist in one place.
Layout in Unity Catalog
There is no single required layout. Two common choices are:
- One catalog per environment, one schema per layer. For example
prod.bronze,prod.silver, andprod.gold. - One catalog per layer. For example
bronze.sales,silver.sales, andgold.sales.
The first option keeps development and production apart. The second makes it easy to grant access by layer at the catalog level. Pick one and apply it consistently, because permissions, naming, and automation all depend on it.
This chapter uses a catalog named main and one schema per layer so the examples run in the workspace used earlier in this tutorial.
CREATE SCHEMA IF NOT EXISTS main.bronze;
CREATE SCHEMA IF NOT EXISTS main.silver;
CREATE SCHEMA IF NOT EXISTS main.gold;Building the bronze layer
Bronze keeps data close to how it arrived. You avoid cleaning here, because any transformation you apply is one you cannot undo if the raw data is gone. It is common to add metadata columns such as the ingestion time and the source file name.
The example below creates a small raw table of order events. The columns are strings on purpose, as raw data from files often arrives untyped. It includes a duplicate and a bad value so there is something to clean.
CREATE TABLE IF NOT EXISTS main.bronze.orders_raw (
order_id STRING,
customer_id STRING,
amount STRING,
order_ts STRING,
ingested_at TIMESTAMP
);
INSERT INTO main.bronze.orders_raw VALUES
('1', '101', '25.00', '2026-12-01 09:15:00', current_timestamp()),
('2', '102', '40.50', '2026-12-01 10:02:00', current_timestamp()),
('2', '102', '40.50', '2026-12-01 10:02:00', current_timestamp()),
('3', '101', 'N/A', '2026-12-02 08:30:00', current_timestamp()),
('4', '103', '12.75', '2026-12-02 11:45:00', current_timestamp());In a real pipeline, bronze is usually filled by an ingestion mechanism such as Auto Loader or a streaming source, and tables are append-only. Appending means that a repeated delivery produces duplicate rows. That is expected, and silver is where you handle it.
Building the silver layer
Silver turns raw records into trustworthy ones. Typical steps are:
- Cast columns to proper types.
- Drop or quarantine rows that fail validation.
- Remove duplicates.
- Standardize names and formats.
The following PySpark code reads bronze, applies those steps, and writes silver.
from pyspark.sql import functions as F
bronze = spark.table("main.bronze.orders_raw")
silver = (
bronze
.select(
F.col("order_id").cast("bigint").alias("order_id"),
F.col("customer_id").cast("bigint").alias("customer_id"),
F.try_to_number(F.col("amount"), F.lit("999999.99")).cast("decimal(10,2)").alias("amount"),
F.to_timestamp("order_ts").alias("order_ts"),
)
.where(F.col("order_id").isNotNull() & F.col("amount").isNotNull())
.dropDuplicates(["order_id"])
)
(
silver.write
.mode("overwrite")
.saveAsTable("main.silver.orders")
)Order 3 is dropped because N/A cannot be converted to a number, and the duplicate of order 2 is removed. Dropping rows silently is risky in real systems. A safer design writes failing rows to a separate quarantine table so you can inspect and repair them.
If try_to_number is not available on your runtime, use F.col("amount").try_cast("decimal(10,2)") instead. Both return null when the value cannot be converted, where a plain cast could raise an error when ANSI mode is on.
Building the gold layer
Gold tables answer a specific business question. They are often aggregated and named for their purpose. The next example computes revenue per customer per day.
CREATE OR REPLACE TABLE main.gold.daily_customer_revenue AS
SELECT
customer_id,
CAST(order_ts AS DATE) AS order_date,
COUNT(*) AS order_count,
SUM(amount) AS revenue
FROM main.silver.orders
GROUP BY customer_id, CAST(order_ts AS DATE);
SELECT * FROM main.gold.daily_customer_revenue ORDER BY order_date, customer_id;A dashboard or a Databricks SQL query can read this table directly. Because the heavy work has already been done, queries are fast and cheap.
Refreshing layers incrementally
The examples above rebuild entire tables. This is fine for small data and for learning, but it gets slow and costly as data grows. Two common approaches are:
- MERGE into silver. Process only new bronze rows and upsert them by key.
- Declarative pipelines or streaming. Define the tables and let the platform track what is new.
An upsert looks like this:
MERGE INTO main.silver.orders AS t
USING (
SELECT
CAST(order_id AS BIGINT) AS order_id,
CAST(customer_id AS BIGINT) AS customer_id,
CAST(try_cast(amount AS DECIMAL(10,2)) AS DECIMAL(10,2)) AS amount,
to_timestamp(order_ts) AS order_ts
FROM main.bronze.orders_raw
WHERE try_cast(amount AS DECIMAL(10,2)) IS NOT NULL
QUALIFY row_number() OVER (PARTITION BY order_id ORDER BY ingested_at DESC) = 1
) AS s
ON t.order_id = s.order_id
WHEN MATCHED THEN UPDATE SET *
WHEN NOT MATCHED THEN INSERT *;The QUALIFY clause keeps only the latest row for each order_id. This matters because MERGE fails if several source rows match the same target row.
Common errors and trade-offs
- Cleaning in bronze. This destroys the raw record. Add columns, but do not change values.
- Too many layers. Some teams add extra layers for every small step. Each layer costs storage and compute and adds more to maintain. Add a layer only when it serves a clear purpose.
- Gold tables with no owner. Gold tables multiply quickly. Give each one a clear purpose and an owner, or consumers will not know which to trust.
- Duplicate source rows in a MERGE. Deduplicate the source first, as shown above.
- Rebuilding everything on every run. This works until volume grows. Move to incremental processing before the cost becomes a problem.
- Ignoring schema changes. Sources add and rename columns. Decide whether bronze stores the payload as-is (for example as a JSON string) or with a fixed schema, and how silver reacts to new fields.
- Unrestricted bronze access. Raw data often holds personal or sensitive fields. Grant access to bronze narrowly and publish cleaned or masked data in silver and gold.
Applying permissions by layer
Unity Catalog permissions follow the layout. If analysts should read only gold, grant them rights on that schema and nothing else.
GRANT USE CATALOG ON CATALOG main TO `data-analysts`;
GRANT USE SCHEMA, SELECT ON SCHEMA main.gold TO `data-analysts`;Without USE SCHEMA and SELECT on the silver and bronze schemas, the group cannot read those tables, even though they sit in the same catalog.
Checking your pipeline
Delta history helps you debug layers. After a run, inspect what changed.
DESCRIBE HISTORY main.silver.orders;If a bad run damaged silver, you can read an earlier version with VERSION AS OF, or restore it with RESTORE TABLE main.silver.orders TO VERSION AS OF 0. Because bronze is intact, you can also simply rebuild silver.
Exercise
A silver table must be rebuilt after you find a bug in the date-parsing logic. Which layer lets you do this without contacting the source system, and why must bronze stay unmodified for this to work?
Show answer
Bronze. It stores the data as it was received, so you can rerun the corrected silver logic against it. If bronze had been cleaned or altered, the original values would be lost and the rebuild could not recover them.
Exercise
A MERGE into silver fails with an error saying multiple source rows matched the same target row. What is the likely cause, and how do you fix it?
Show answer
Bronze is append-only and holds several rows with the same key, such as repeated deliveries. Deduplicate the source before the MERGE, for example with row_number() over a partition by the key ordered by ingestion time, and keep only the first row.
Exercise
Analysts have USE CATALOG on main and SELECT on main.gold. They try to query main.silver.orders. What happens, and what would you grant to allow it?
Show answer
The query fails with a permission error, because they have no privileges on the silver schema. Grant USE SCHEMA and SELECT on main.silver (or on the table) to their group, but only if the business needs them to read cleaned detail data.