🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Data Warehouse: BigQuery, Partitioning, Clustering & Optimization

GCP Data EngineeringData WarehouseđŸŸĸ Free Lesson

Data Warehouse: BigQuery Deep Dive

Master BigQuery data warehouse including schema design, partitioning, clustering, materialized views, and performance optimization.

22 min readAdvanced

What You'll Learn

  • 1Explain how columnar storage and slots shape the cost of a BigQuery workload
  • 2Choose a partitioning and clustering key from the query patterns rather than the schema
  • 3Implement an SCD Type 2 dimension with a single MERGE statement
  • 4Apply the layout tools in order: partition, cluster, materialize, cache

What the Warehouse Layer Actually Decides

A warehouse is a bet about which questions will be asked. BigQuery stores each column separately in a columnar format, so a query touching three of fifty columns reads roughly three fiftieths of the table instead of all of it, and the charge follows bytes scanned rather than machines started. Compute is a pool of slots: a query is split into stages, each stage claims slot time, and on demand billing totals the slot milliseconds consumed. Two consequences shape everything else here. A query cannot be made cheaper by moving it to a smaller machine, because the machine is abstract; it is made cheaper by reading fewer bytes. And because storage and compute scale independently, storing a table at two cents per GB-month while querying it for a few cents a day is normal, which is why copying data into a narrow analytic table usually beats adding an operational index to the source.

Modelling follows the storage engine. A star schema keeps one wide fact table of events beside small dimension tables of context, and BigQuery prefers it because columnar storage makes a join against a narrow dimension cheap, while a normalized snowflake schema adds join stages and shuffles for no read benefit. Dimension columns that analysts filter on are then denormalized into the fact table, trading a little duplication for a shorter query plan.

Schema Design Patterns

The DDL below shows two habits worth copying: every key carries a description, and the fact table declares partitioning, clustering and the partition filter at creation time, so the guard rails exist before the first analyst connects.

-- Fact table: Sales transactions
CREATE TABLE `project.warehouse.fact_sales`
(
  sale_key INT64 OPTIONS(description="Surrogate key"),
  order_id STRING OPTIONS(description="Natural key"),
  customer_key INT64 OPTIONS(description="FK to dim_customer"),
  product_key INT64 OPTIONS(description="FK to dim_product"),
  quantity INT64,
  unit_price FLOAT64,
  discount_amount FLOAT64,
  total_amount FLOAT64,
  sale_timestamp TIMESTAMP,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP()
)
PARTITION BY DATE(sale_timestamp)
CLUSTER BY customer_key, product_key
OPTIONS(
  description="Sales fact table partitioned by date",
  require_partition_filter = true
);

-- Dimension table: SCD Type 2 customers
CREATE TABLE `project.warehouse.dim_customer`
(
  customer_key INT64 OPTIONS(description="Surrogate key"),
  customer_id STRING OPTIONS(description="Natural key"),
  customer_name STRING,
  segment STRING,
  region STRING,
  effective_date DATE,
  expiry_date DATE,
  is_current BOOLEAN DEFAULT TRUE
)
OPTIONS(description="SCD Type 2 customer dimension");

A surrogate key such as customer_key exists so a dimension change does not rewrite history: the fact table keeps pointing at the key that was valid when the sale happened while the dimension accumulates new rows. Keep fact tables narrow and numeric, push free text into a dimension, and store times as TIMESTAMP rather than strings so pruning and filters work without a cast.

Partitioning, Clustering and Pruning

Partitioning divides a table into independent units a query can skip. Clustering sorts rows inside each partition by a second set of columns so the scan touches fewer column chunks. The arithmetic makes the choice obvious: a two year daily partitioned fact table holds about seven hundred and thirty partitions of a few gigabytes each, and a query filtered to one day reads roughly one seven hundred thirtieth of the table instead of all of it.

-- Daily partitions plus clustering on the columns dashboards filter by
CREATE TABLE `project.warehouse.events_partitioned`
(
  event_id STRING,
  event_type STRING,
  user_id STRING,
  event_timestamp TIMESTAMP,
  payload JSON
)
PARTITION BY DATE(event_timestamp)
CLUSTER BY event_type, user_id
OPTIONS (
  partition_expiration_days = 730,
  require_partition_filter = true
);

-- Inspect how partitions actually landed
SELECT partition_id, row_count, storage_tier
FROM `project.warehouse`.INFORMATION_SCHEMA.PARTITIONS
WHERE table_name = 'events_partitioned'
ORDER BY partition_id DESC
LIMIT 10;

BigQuery allows four thousand partitions per table, so daily partitions over a decade fit comfortably while per second partitions would not. Clustering accepts up to four columns and works best when the leading column has thousands of distinct values, because pruning happens in sorted block order; a low cardinality column such as a boolean belongs in a filter, not in the clustering key. Clustering is also dynamic, so a table re-sorts as data is added, whereas a partition scheme chosen at creation time is expensive to change later. Decide partitions from the time range most queries restrict, then decide clusters from the columns those queries filter or group after the date filter.

SCD Type 2 with a Single Merge

Type 2 slowly changing dimensions keep every historical version of a row instead of overwriting it, which is what lets a report show the segment a customer was in when the order was placed.

MERGE `project.warehouse.dim_customer` AS target
USING (
  SELECT
    customer_id, customer_name, segment, region,
    CURRENT_DATE() AS effective_date
  FROM `project.staging.customer_changes`
) AS source
ON target.customer_id = source.customer_id AND target.is_current
WHEN MATCHED AND (
  target.segment != source.segment OR target.region != source.region
) THEN UPDATE SET
  target.is_current = FALSE,
  target.expiry_date = DATE_SUB(source.effective_date, INTERVAL 1 DAY)
WHEN NOT MATCHED THEN
  INSERT (customer_id, customer_name, segment, region, effective_date, expiry_date, is_current)
  VALUES (source.customer_id, source.customer_name, source.segment, source.region,
          source.effective_date, DATE '9999-12-31', TRUE)
WHEN NOT MATCHED BY SOURCE AND target.is_current THEN
  UPDATE SET target.is_current = FALSE,
             target.expiry_date = DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY);

Run it inside a transactional script or a scheduled Dataform model, and always compare on the attributes rather than on a hash alone, because a hash mismatch without a real change would create a duplicate version. Reports then join with a predicate on is_current for the latest view or with effective_date <= order_date AND order_date < expiry_date for the point in time view, which is the whole reason the surrogate key exists.

Four Ways to Make the Same Query Cheaper

Each mechanism attacks a different cost, and applying them in the wrong order wastes money: caching a query that still scans a terabyte helps nobody, and materializing a table that already prunes to one partition doubles storage for nothing.

MechanismWhat it removesLimit to knowApplies when
Partition pruningBytes from untouched time rangesMax 4,000 partitions per tableMost queries filter a date
Cluster pruningBytes within a partitionUp to 4 clustering columnsFilters on high cardinality keys
Materialized viewRecomputed joins and aggregationsMust derive from base tables, refresh on writeDashboard aggregates repeat hourly
BI Engine cacheExecution time of hot queriesReservation sized in memory, boundedSub second latency on a fixed set
Result cacheThe whole query for repeat readersSame SQL and same table version within 24 hoursScheduled reports rerun unchanged

The result cache deserves mention because it is free and frequently overlooked: an identical query run within twenty four hours of the previous run, against an unchanged table, is served from cache and billed at zero bytes. That is why a dashboard refreshed every minute appears to cost nothing until someone edits the underlying table, at which point every cache entry invalidates and the real bill returns.

Materialized Views and Automatic Rewrite

A materialized view stores the result of an aggregation and refreshes when the base table changes, but its most useful property is that BigQuery rewrites compatible queries to read it transparently, so no dashboard definition has to change.

CREATE MATERIALIZED VIEW `project.warehouse.mv_daily_sales`
PARTITION BY DATE(day)
CLUSTER BY product_category
AS
SELECT
  DATE(order_date) AS day,
  product_category,
  COUNT(*) AS order_count,
  SUM(total_amount) AS total_revenue,
  AVG(total_amount) AS avg_order_value
FROM `project.warehouse.fact_sales`
GROUP BY 1, 2;

-- Force a rebuild after a backfill
ALTER MATERIALIZED VIEW `project.warehouse.mv_daily_sales` REFRESH;

-- Confirm the rewrite actually happened in the job statistics
SELECT
  job_id,
  statement_type,
  total_bytes_processed
FROM `region-us`.INFORMATION_SCHEMA.JOBS_BY_USER
WHERE statement_type = 'SELECT'
  AND creation_time >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 1 DAY)
ORDER BY creation_time DESC
LIMIT 20;

Rewrite rules are strict: the query must aggregate only columns present in the view, join keys must match, and any extra filter that the view cannot satisfy falls back to the base tables. A common surprise is that a view over a partitioned table cannot be queried without a partition filter if the base table requires one, so the guard rail travels through the materialization rather than being lost.

Cost Controls That Actually Bite

Four controls prevent the bill from becoming a surprise, and three of them are configuration rather than discipline. require_partition_filter on every large table makes a forgotten date filter a query error instead of a full scan. Selecting named columns instead of SELECT * keeps wide payload columns out of the read. A maximum bytes billed set on ad hoc projects stops a cartesian join from consuming a day's budget in a minute. And for predictable workloads, BigQuery editions replace on demand pricing with a reserved slot pool: the platform keeps a floor for steady jobs and an autoscaling ceiling for spikes, which is cheaper than paying the on demand rate for a query pattern you can forecast.

✨

Best Practice: Always partition large tables by the date most queries filter, cluster by the columns those queries restrict afterwards, and set require_partition_filter so an unfiltered scan fails instead of billing. Use materialized views for dashboard aggregates, keep BI Engine reserved for the handful of queries that need sub second latency, and avoid SELECT * on wide tables.

Common Interview Questions

Q1: Partitioning versus clustering?

Answer: Partitioning splits a table into up to four thousand independent units, normally by date, so whole units are skipped. Clustering sorts rows inside each partition by up to four columns so scans prune within a unit. Partition on the time range nearly every query restricts, cluster on the high cardinality keys those queries then filter.

Q2: Star schema or snowflake schema?

Answer: Star schema, because BigQuery's columnar storage makes a join against a narrow dimension cheap while snowflaking adds join stages, shuffles and a harder query surface for analysts. Normalize in the transformation layer and publish denormalized tables for consumption.

Q3: How do you implement SCD Type 2?

Answer: With one MERGE statement that closes the current row by setting is_current false and an expiry date, then inserts the new current row when an attribute actually changed. Join on the surrogate key for the latest view, or bracket the order date between effective_date and expiry_date for point in time reporting.

Q4: What does require_partition_filter protect against?

Answer: It forces every query to carry a partition predicate, so a missing date filter becomes an error the author fixes immediately rather than a scan that reads the whole table and bills accordingly. It can be bypassed for a deliberate maintenance job, which makes the exception visible in the logs.

Q5: How would you cut warehouse cost this week?

Answer: Add partition filters to the top queries by bytes scanned from INFORMATION_SCHEMA.JOBS, cluster the two largest tables by their most filtered columns, replace the recurring dashboard aggregates with materialized views, turn off SELECT * in the Looker explores, and move the steady nightly workload onto a reserved slot pool instead of on demand pricing.

Interview Questions

Q1: Why does clustering order matter more than the number of clustering columns?

Pruning walks the sorted blocks of the first column before it looks at the second, so a low cardinality leading column prunes almost nothing and wastes the remaining three slots in the key.

Q2: When will BigQuery not rewrite a query to use a materialized view?

When the query touches a column the view does not contain, joins on a key the view lacks, or applies a filter that cannot be derived from the view definition, in which case the base tables are read and the cost returns.

Q3: How do you decide between on-demand and editions?

Compare measured slot hours from the quota page against the reserved rate: predictable steady workloads with a known floor favour a reservation, while spiky or exploratory projects stay cheaper on demand with a maximum bytes billed guard.

Q4: What is the point of a surrogate key in the dimension?

It decouples history from the business identifier so a segment change does not rewrite past orders; facts keep the key that was current when the event happened and the dimension grows a new version.

Common Mistakes

Partitioning by a column with thousands of values a day

Fix: Use time based partitions and cluster the high cardinality columns instead, or the table hits the four thousand partition ceiling within weeks.

Materializing every dashboard query

Fix: Materialize only aggregates that repeat and are expensive to recompute, then check the rewrite in job statistics to confirm the view is being used.

Leaving ad hoc projects on unlimited on-demand scanning

Fix: Set maximum bytes billed per query so a runaway join fails fast, and move the predictable nightly load onto reserved slots.

Key Takeaways

  • BigQuery bills bytes scanned and slot time, so every optimisation aims at reading fewer column chunks rather than running on a smaller machine
  • Partition up to four thousand units by time, cluster up to four high cardinality columns afterwards, and enforce the date filter with require_partition_filter
  • SCD Type 2 is one MERGE that closes the old row and inserts the new one, which preserves point in time reporting through the surrogate key
  • Partitioning, clustering, materialized views, BI Engine and the free result cache attack different costs and should be applied in that order
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert GCP Data Engineering Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement