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

BigQuery Optimization: Partitioning, Clustering & Slot Management

GCP Data EngineeringBigQuery PerformanceđŸŸĸ Free Lesson

BigQuery Performance Optimization

Master BigQuery performance optimization including partitioning, clustering, slot management, query optimization, and cost control.

20 min readAdvanced

What You'll Learn

  • 1Trace a BigQuery bill back to bytes billed, slot milliseconds, and storage so each lever is obvious
  • 2Design a partition key and clustering order that makes the common query prune by default
  • 3Read an execution plan and spot shuffle, skew, and broadcast opportunities before tuning SQL
  • 4Choose between cached results, materialized views, and BI Engine for a given dashboard

Speed in BigQuery is mostly a question of how much data a query is allowed to touch and how many slots it touches it with. Two tables with identical rows can differ by an order of magnitude in cost purely because one is partitioned on the column every filter uses. This lesson works through the billing model first, because every tuning decision below is a way of reducing bytes billed or slot time, then the physical layout options, then the dashboards you watch to keep the gains.

What a query actually costs

On-demand pricing charges for bytes scanned, rounded to the nearest megabyte per table, while editions and committed capacity charge for slot milliseconds consumed. The same query that looks cheap in one model can be expensive in the other: a wide scan that finishes quickly may burn few slots but bill a lot of bytes, whereas a small query wedged behind a congested reservation consumes slots for minutes.

# Cost before execution: prints bytes and the equivalent dollar estimate
bq query --dry_run --use_legacy_sql=false "
  SELECT event_type, COUNT(*)
  FROM \`project.dataset.events\`
  WHERE event_date = '2025-01-15'
  GROUP BY 1"

Put the dry run into your deployment pipeline and fail the build when a model's bytes billed jumps. The other half of the bill is storage, where long term storage costs about half of active storage after data has not been modified for ninety days, so partition expiry and lifecycle policies matter as much as query tuning for tables nobody reads.

Partitioning cuts whole segments away

A partitioned table is physically split into segments, up to four thousand of them, and a filter on the partition column lets BigQuery skip segments entirely rather than scanning them. Daily time unit partitioning is the default choice for event tables; integer range partitioning suits ids or measured values with known bounds.

CREATE TABLE `project.dataset.events`
PARTITION BY DATE(event_timestamp)
OPTIONS (
  partition_expiration_days = 730,
  require_partition_filter = true
);

-- Integer range partitioning for id-shaped columns
CREATE TABLE `project.dataset.sales`
PARTITION BY RANGE_BUCKET(sale_id, GENERATE_ARRAY(0, 10000000, 100000));

SELECT event_type, COUNT(*)
FROM `project.dataset.events`
WHERE event_date >= '2025-01-01'      -- partition pruning
  AND event_type = 'purchase';         -- resolved inside each partition

Set require_partition_filter on every partitioned table you care about. It makes an unfiltered query fail instead of silently scanning two years of history, which is the single highest leverage setting in the service. If the table receives heavy daily writes, prefer a partition column that matches the write pattern, because a table partitioned by an arbitrary id ends up with thousands of nearly empty partitions and no pruning benefit.

Clustering orders data inside a partition

Clustering sorts rows within each partition by up to four columns in priority order, and it is the right tool when filters use several columns at once or when the values are high cardinality such as a customer id. Clustering metadata records the min and max of each column per storage block, so pruning happens at block granularity during the scan.

CREATE TABLE `project.dataset.sales`
PARTITION BY DATE(order_date)
CLUSTER BY customer_id, product_id, region;

SELECT customer_id, SUM(amount) AS total
FROM `project.dataset.sales`
WHERE order_date = '2025-01-15'
  AND customer_id = 'user_123'
  AND region = 'US';

Clustering is not free. Every write pays the ordering cost, and after enough updates BigQuery reclusters automatically when a partition has changed by more than ten percent, which shows up as background slot usage you did not ask for. Cluster on columns that appear in equality filters and in join keys, keep the leading column the most selective one, and never cluster a column that only ever appears in a GROUP BY you run once a quarter.

Reading the plan before rewriting SQL

Every tuned query deserves an execution plan, and BigQuery will give you one without running the job. Stages that exchange rows are where skew hides: if one worker reads far more than its peers, the join key is lopsided and the fix is usually to filter earlier or to denormalise rather than to add slots.

-- Broadcast the small side instead of shuffling the large one
SELECT /*+ BROADCAST(p) */
  o.order_id,
  p.product_name
FROM `project.dataset.orders` o
JOIN `project.dataset.small_products` p
  ON o.product_id = p.product_id
WHERE o.order_date >= '2025-01-01';

-- Approximate aggregates when the exact number costs a shuffle
SELECT APPROX_COUNT_DISTINCT(user_id) AS users
FROM `project.dataset.events`
WHERE event_date = '2025-01-15';

The usual suspects, in order: a wildcard or unfiltered scan, a join on an unclustered high cardinality column, a DISTINCT that a GROUP BY would have handled, and a UDF applied row by row that could be expressed in native SQL. Rewrite in that order before touching capacity settings.

Caching, materialized views, and BI Engine

Four mechanisms reduce repeated work, and they fail in different ways, so pick by access pattern rather than by fashion.

TechniqueWhat it storesInvalidated byBest forWatch out for
Cached resultsLast query result, roughly a dayAny table change, and after 24 hoursIdentical reruns from dashboardsMisses on a whitespace change in the SQL
Materialized viewPrecomputed aggregate over base tablesBase table writes, plus explicit reflectionDaily aggregates over a large fact tableNot every query shape can be rewritten to use it
BI EngineHot table partitions in memoryReservation changes and evictionSub-second interactive dashboardsYou reserve capacity in gigabytes whether it is used or not
Search indexPer column inverted indexRow updatesText search and pattern matchingOnly helps predicates it supports

A materialized view is the workhorse for a dashboard that repeats the same aggregation: BigQuery rewrites eligible queries to read it and refreshes it when base tables change. Reserve BI Engine for a handful of tables where interactivity is the product, because the reservation bills whether or not users open the dashboard that day.

Rewrites, time travel, and safe migrations

Performance gains are easy to lose in a migration script. A CREATE OR REPLACE that drops the clustering clause hands you a table with identical rows and no ordering, and every dashboard query slows down in the same afternoon. Copy the partition and clustering clauses into the new DDL, and prefer a scheduled backfill over an in-place mutation for large tables so the swap happens in one statement that either succeeds or leaves the original untouched.

BigQuery keeps seven days of time travel by default, which turns a mistaken delete into a recoverable event rather than an incident, and table snapshots extend that protection beyond the window without duplicating the full cost of a copy. Take a snapshot before any destructive migration, verify row counts against it, and drop it when the retention rule says the old data may go. The same habit protects clustering metadata: a snapshot restores the layout you tuned, not just the rows.

Slots, reservations, and the monitoring you keep

Under editions you buy slot capacity and share it through reservations and assignments, so the number that matters is slot milliseconds per query divided by useful work. Query a project's job history to find the expensive repeat offenders.

SELECT
  job_creation_time,
  job_id,
  user_email,
  total_bytes_billed,
  slot_ms_used,
  ROUND(slot_ms_used / 1000 / 60, 2) AS slot_minutes
FROM `region-us-central1`.INFORMATION_SCHEMA.JOBS_BY_PROJECT
WHERE DATE(job_creation_time) = CURRENT_DATE()
  AND job_type = 'QUERY'
ORDER BY slot_ms_used DESC
LIMIT 50;

SELECT
  TIMESTAMP_TRUNC(timestamp, MINUTE) AS minute,
  AVG(num_slots) AS avg_slots,
  MAX(num_slots) AS max_slots
FROM `region-us-central1`.INFORMATION_SCHEMA.JOBS_TIMELINE
WHERE timestamp >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 1 HOUR)
GROUP BY 1
ORDER BY 1;

Pair those two views with an alert on bytes billed per day. When average slot utilisation sits near zero while you are paying for capacity, the reservations are oversized or misassigned; when it pegs at the reservation ceiling, either the autoscaling queue is too small or a handful of analysts are running the unfiltered scans that require_partition_filter exists to prevent.

Common Mistakes

Running SELECT star over an event table to see what is in it

Fix: Add a partition filter and dry run first, since a single unfiltered scan can cost more than a week of filtered ones.

Clustering on a low cardinality column such as a boolean

Fix: Cluster on selective columns used in equality filters and joins; low cardinality values repeat in every block and prune nothing.

Adding slots to fix a query that shuffles badly

Fix: Read the plan, filter before the join, and broadcast the small side; capacity hides skew instead of removing it.

Best Practices

  • Set require_partition_filter on every partitioned table and enforce it in code review
  • Dry run new SQL in CI and fail the build on unexpected bytes billed
  • Review INFORMATION_SCHEMA.JOBS_BY_PROJECT weekly and delete queries that scan more than they return

Key Takeaways

  • On-demand billing follows bytes scanned while capacity billing follows slot milliseconds, so each has its own tuning path
  • Partitioning prunes whole segments, limited to four thousand partitions, and clustering prunes blocks within them
  • require_partition_filter converts an accidental full scan into an error the user sees immediately
  • Cached results, materialized views, and BI Engine differ by what invalidates them, not by how fast they start

Interview Questions

Q1: What is the difference between partitioning and clustering?

Partitioning splits a table into segments, up to four thousand, on one column such as a date, and a filter on it skips whole segments. Clustering sorts rows inside each segment by up to four columns and prunes storage blocks by min and max metadata. Most tables use both: partition on time, cluster on the join or filter keys.

Q2: How do you prevent an expensive query from reaching production?

Set require_partition_filter on the tables, add maximum_bytes_billed to job submissions so over-budget jobs abort, dry run in CI to catch regressions, and select only the columns you need instead of star.

Q3: When should you use a materialized view?

When the same aggregate over a large base table repeats and the query shape can be rewritten to read the view. It refreshes automatically as base tables change, unlike a manual table you rebuild, and it costs storage but saves bytes on every hit.

Q4: How do you optimise a join in BigQuery?

Filter both sides on partition columns before joining, cluster on the join key, broadcast the small side with a BROADCAST hint when one input is under about a gigabyte, and consider denormalising a stable dimension so the join disappears.

Q5: What does slot utilisation tell you that bytes billed does not?

Bytes billed measures work requested; slot milliseconds measure how long the engine was occupied. A query can scan little data yet hold slots for minutes because of skew or an expensive UDF, which capacity planning has to see separately from cost per query.

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