Sub topic 10
Gold: tables shaped for business consumers
This chapter assumes you have read the bronze and silver chapters. You should know that main.silver.orders holds typed, deduplicated orders, with one row per order_id. You should also be comfortable with GROUP BY aggregates and with Delta tables in Unity Catalog.
What the gold layer is for
Silver answers "what happened, cleanly." Gold answers a specific business question. A gold table is built for one consumer or one family of consumers, such as a finance dashboard, a marketing segmentation job, or a machine-learning feature pipeline.
This changes how you design the layer:
- Silver is shaped by the source data. Gold is shaped by the question.
- Silver keeps detail. Gold usually aggregates, joins, and renames until the table is easy to query.
- Silver is read mostly by data engineers. Gold is read by analysts, BI tools, and applications that should not need to know how the data was cleaned.
A good gold table lets a consumer run a simple SELECT and get a correct, agreed-upon number.
Design from the consumer backward
Before writing SQL, settle four things with the people who will use the table.
- Grain. The grain is what one row represents. "One row per day" and "one row per customer" are different tables. If you cannot state the grain in one sentence, the table is not ready to build.
- Metric definitions. Decide what "revenue" means. Does it include refunds? Does it include only completed orders? Write the rule into the query and into the table comment, so the definition lives in one place.
- Time semantics. Choose which timestamp defines a "day" and which time zone applies.
CAST(order_ts AS DATE)uses the session time zone. Two clusters with different settings can produce different daily totals. - Freshness. Ask how stale the numbers may be. A nightly refresh and a 5-minute refresh lead to different designs.
Write these decisions down. Most gold-layer bugs are disagreements about definitions, not code errors.
A worked example: daily revenue
This table aggregates completed orders from silver into one row per day.
CREATE OR REPLACE TABLE main.gold.daily_revenue AS
SELECT
CAST(order_ts AS DATE) AS order_date,
COUNT(*) AS orders,
SUM(amount) AS revenue
FROM main.silver.orders
WHERE status = 'completed'
GROUP BY CAST(order_ts AS DATE)Some points about this query:
- The grain is one row per
order_date.GROUP BYenforces it, so a dashboard cannot accidentally double-count a day. - The filter encodes a business rule. Only
completedorders count as revenue. Any consumer who reads this table gets the same rule. SUM(amount)stays exact. The silver step castamounttoDECIMAL(12,2), so sums do not accumulate floating-point error. This is why typing happens in silver, before aggregation.CREATE OR REPLACE TABLEis atomic. Readers keep seeing the previous version until the new one commits. They never see a half-written table.
A second gold table over the same silver data serves a different consumer. This one has one row per customer.
CREATE OR REPLACE TABLE main.gold.customer_orders_summary
COMMENT 'One row per customer. Lifetime metrics over completed orders only.'
AS
SELECT
customer_id,
COUNT(*) AS orders,
SUM(amount) AS lifetime_revenue,
MIN(order_ts) AS first_order_ts,
MAX(order_ts) AS last_order_ts
FROM main.silver.orders
WHERE status = 'completed'
GROUP BY customer_idThe two tables overlap in their data, but they do not overlap in purpose. Do not try to serve both consumers with one table that has every column. Such a table is hard to document, hard to keep correct, and hard to change without breaking someone.
Choosing a refresh strategy
There are three common ways to keep a gold table current.
| Strategy | How it works | Good when | Watch out for |
|---|---|---|---|
| Full rebuild with `CREATE OR REPLACE TABLE` | Recompute the whole table from silver each run | Silver is small or moderate, and the logic is simple | Cost grows with silver size, because every run rereads everything |
| Incremental `MERGE` | Recompute only the affected keys (for example, the days that changed) and upsert them | The table is large and changes touch few keys | You must identify the affected keys correctly, or the table drifts |
| Materialized view or declarative pipeline table | Databricks tracks changes and refreshes the result for you, incrementally when it can | You want less hand-written refresh logic | Supported query shapes are limited, and some features need specific compute |
Start with a full rebuild. It is the easiest to reason about, and it is always correct as long as silver is correct. Move to something incremental when run time or cost makes you. A materialized view version of the daily revenue table looks like this:
CREATE MATERIALIZED VIEW main.gold.daily_revenue_mv AS
SELECT
CAST(order_ts AS DATE) AS order_date,
COUNT(*) AS orders,
SUM(amount) AS revenue
FROM main.silver.orders
WHERE status = 'completed'
GROUP BY CAST(order_ts AS DATE)Materialized views in Unity Catalog run on specific compute, such as a SQL warehouse or a pipeline. Check the current documentation for the requirements in your workspace.
Edge cases that affect gold correctness
Late and changing data. An order that was pending yesterday may be completed today. A full rebuild handles this automatically. An incremental job that only reprocesses "today" will leave yesterday's total wrong. When you go incremental, recompute every date that any changed silver row touches, not only the newest date.
Days with no orders. GROUP BY produces no row for a day without completed orders. A chart may show a gap or a misleading line. If consumers need every day, join against a calendar table so that missing days appear with zero values.
Cancelled and refunded orders. With the filter status = 'completed', a later refund does not reduce revenue unless silver records it in a way gold accounts for. State the rule in the table comment. If finance needs net revenue, build that as a separate, clearly named column or table.
Duplicates leaking from silver. If silver has two rows for one order_id, gold sums both. Gold should trust silver, so fix the duplicate at its source. Adding DISTINCT in gold hides the problem.
Schema changes in silver. Renaming a silver column breaks every gold query that uses it. Gold queries that name their columns explicitly fail loudly, which is better than silently wrong results.
Making gold easy to consume
Small choices make a table pleasant to use.
- Use business names.
revenueandorder_dateare better thansum_amountanddt. - Add comments. Put
COMMENTon the table and on columns that carry a business rule. Analysts see these in Catalog Explorer. - Keep the table narrow and flat. Precompute joins so a BI tool does not have to join five tables to answer one question.
- Do not expose internal columns. Load metadata such as
_ingested_atand_source_filebelongs in bronze and, if needed, silver. Leave it out of gold. - Pick stable table names. Dashboards depend on them. If you must change a table's meaning, create a new table and retire the old one on a schedule.
Governing and maintaining gold
Gold is usually the only layer analysts can read, so permissions follow from that. Grant SELECT on the main.gold schema to the analyst group, and leave bronze and silver restricted to the engineering team. The access chapter covers the grants in detail.
Gold tables are also the most queried, so they benefit most from maintenance such as file compaction. The table maintenance chapter covers that.
Since gold is rebuilt from silver, it is the cheapest layer to lose. If a gold table is wrong or deleted, fix the logic and rebuild it. This is one reason to keep business logic in versioned code and not in manual edits to the table.
Common pitfalls
- One giant gold table for everyone. It becomes impossible to explain and to change. Prefer several focused tables.
- Business logic scattered across dashboards. Two dashboards compute "revenue" differently. Move the definition into gold so there is one answer.
- Skipping the grain statement. Without it, joins fan out and totals double.
- Aggregating before cleaning. Gold built directly on bronze inherits every defect. Always read from silver.
- Rebuilding too eagerly. A full rebuild every 5 minutes over a large silver table wastes money. Match the refresh frequency to what consumers need.
Exercise
The marketing team asks for a table showing, for each customer, the number of completed orders and the date of their most recent completed order. State the grain of the gold table, then write the query against main.silver.orders. Finally, explain why an incremental job that refreshes only today's data would be a poor choice for a daily revenue table.
Show answer
The grain is one row per customer (customer_id). The query is:
CREATE OR REPLACE TABLE main.gold.customerlastorder AS
SELECT
customerid,
COUNT(*) AS completedorders,
CAST(MAX(orderts) AS DATE) AS lastorderdate
FROM main.silver.orders
WHERE status = 'completed'
GROUP BY customerid
A job that refreshes only today's data is a poor choice for daily revenue because silver rows for earlier days can change. An order from yesterday may move from pending to completed today, and then yesterday's total is wrong. An incremental job must recompute every date touched by changed silver rows, or it can fall back to a full rebuild.