Installation

Install as Agent Plugin Recommended
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install bigquery-optimization@skills-hub

Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled). Plugin bigquery-optimization v1.0.0 follows the Agent Plugins spec.

Install with the gh extension
gh skills-hub install bigquery-optimization

Don't have the extension? Run gh extension install samueltauil/skills-hub first.

Download and extract to your repository:

.github/skills/bigquery-optimization/

Extract the ZIP to .github/skills/ in your repo. The folder name must match bigquery-optimization for Copilot to auto-discover it.

Skill Files (10)

SKILL.md 9.3 KB
---
name: bigquery-optimization
metadata:
  version: "1.1.1"
  category: BigDataAndAnalytics
description: >-
  Provides workflows to optimize BigQuery environments (capacity planning,
  editions), storage assets (partitioning, clustering, storage lifecycles,
  billing models), and SQL queries. Use when optimizing cost, modeling Edition
  migrations, rightsizing reservations, evaluating logical vs. physical storage,
  designing table partitioning/clustering, generating table DDL, migrating
  unpartitioned tables, managing partition expiration, optimizing individual SQL
  queries, or evaluating acceleration structures (search indexes, materialized
  views, BI Engine).

  Do not use for raw usage reporting (use bigquery-observability), query
  execution plan analysis, error troubleshooting, or diagnosing why a specific
  job was slow (use bigquery-troubleshooting).
---

# BigQuery Optimization Workflow

## Attribution

**MUST READ**: Before executing any `gcloud`, REST API, or MCP command, you
MUST read [Usage Attribution](references/attribution.md). For commands executed
directly in the terminal (never in generated scripts, Terraform, or user code),
prefix `gcloud` with
`CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:bigquery-optimization)"`
and append `agent-skills/1.0 (skill:bigquery-optimization)` to `User-Agent` headers.

## Prerequisites & Environment Setup

Before executing optimization analyses, evaluating editions, or applying DDL
modifications:

1.  **Google Cloud SDK**: Ensure the
    [Google Cloud SDK](https://cloud.google.com/sdk/docs/install) is installed
    and configured.
2.  **Project Selection**: Set the active Google Cloud project:

    ```bash
    gcloud config set project {project_id}
    ```

3.  **API Enablement**: Ensure BigQuery and BigQuery Reservation APIs are
    enabled:

    ```bash
    gcloud services enable \
        bigquery.googleapis.com bigqueryreservation.googleapis.com
    ```

4.  **Authentication**: Authenticate the environment:
    *   CLI tools and `bq` commands: `gcloud auth login`
    *   SDKs and automation: `gcloud auth application-default login`
    *   Service accounts: Set
        `GOOGLE_APPLICATION_CREDENTIALS="/path/to/key.json"`

5.  **Billing & IAM Roles**:
    *   Verify an active Google Cloud Billing account is attached to
        `{project_id}`.
    *   Ensure appropriate IAM roles:
        *   `roles/bigquery.admin` or `roles/bigquery.resourceAdmin`:
            Reservation and capacity commitment management.
        *   `roles/bigquery.dataEditor` or `roles/bigquery.admin`: Modifying
            table schemas, partitioning, clustering, and storage billing
            models.
        *   `roles/bigquery.jobUser`: Running evaluation queries.

6.  **Companion Skills Installation**:
    This skill is part of a 3-pillar operations suite (`bigquery-observability`,
    `bigquery-optimization`, `bigquery-troubleshooting`). If any companion skill
    is not yet installed in your environment, install the full suite:

    ```bash
    npx skills add google/skills --skill bigquery-observability --skill bigquery-optimization --skill bigquery-troubleshooting
    ```

    *(If `bigquery-observability` is not installed, use the self-contained
    baseline formulas and query templates provided directly in the reference
    sections below).*

## Workflows

Determine the optimization focus of the user's request and follow the relevant
workflow:

-   **Telemetry & Observability Baseline:** For direct raw usage telemetry,
    `INFORMATION_SCHEMA` queries, and baseline metric calculations, consult
    [bigquery-observability](../bigquery-observability)
    (`bigquery_observability`). If the `bigquery-observability` companion skill
    is not available in the active environment, all optimization guidelines, DDL
    templates, and decision models across this skill and its reference guides
    are fully self-contained.
-   **Capacity & Editions Modeling:** Evaluate the cost-efficiency of migrating
    workloads from On-Demand to Editions, as well as rightsizing active Edition
    reservations, baseline commitments, and autoscaling caps.
    *   *Instructions:* Read `references/capacity_planning_editions.md` to
        provide deep links to BigQuery's built-in recommendation UIs (e.g., Slot
        Estimator) and guide the user through UI navigation: 1. navigate to the
        Slot Estimator tab, 2. select 'On-Demand' as the source to analyze
        historical query volume, and 3. review the Cost-Optimized
        Recommendations and Slot Usage Chart.
-   **Table & Storage Optimization:** Optimize storage costs from a billing
    model, physical layout, and lifecycle perspective.
    *   *Billing Architecture:* Read `references/storage_billing_models.md` for
        guidance on evaluating aggregate compression ratios (e.g. >2:1 threshold
        in US) to recommend Physical vs. Logical billing, noting that the
        break-even ratio depends on specific regional rates and custom
        enterprise contracts. When providing `TABLE_STORAGE` queries, always
        scope with `WHERE table_schema = '{dataset_id}'`, use the regional
        dataset view, and warn that 0 rows indicates a region mismatch or lack
        of native tables rather than zero billable usage.
    *   *Partitioning & Clustering Strategy:* Read
        `references/table_partitioning_clustering.md` to generate production DDL
        templates (CREATE TABLE, CTAS migrations for unpartitioned tables, and
        modifying clustering specifications), enforce pruning with
        `require_partition_filter = true`, and manage partition limits (up to
        10,000 partitions/table).
    *   *Lifecycle Management:* Read
        `references/storage_lifecycle_management.md` to pinpoint inactive data
        and define precise Time-to-Live (TTL) partition expirations, dataset
        expirations, and Time Travel window reductions.
    *   *Acceleration Structures:* Read `references/search_indexes.md` to decide
        when to propose a search index for selective lookups over `STRING` or
        `JSON` data, write the `CREATE SEARCH INDEX` DDL, and tell the user how
        to verify index coverage and usage. Read
        `references/materialized_views.md` to decide when to propose a
        materialized view for repeated aggregations or joins over large base
        tables, write the `CREATE MATERIALIZED VIEW` DDL, and tell the user how
        to verify that smart tuning uses it. Read `references/bi_engine.md` to
        decide when to propose BI Engine vs. Materialized Views for BI dashboard
        acceleration, diagnose `PARTIAL` or `DISABLED` BI Engine fallback
        reasons (`bi_engine_statistics`), and combine BI Engine with
        materialized views that pre-join or pre-aggregate the data.
-   **SQL Optimization:** Optimize individual SQL queries to reduce slot-time
    and the amount of data read.
    *   *Instructions:* Follow the instructions in
        `references/sql_optimization.md` to provide recommendations to the user
        on how to rewrite their SQL query to reduce slot-time and the amount of
        data read.

## Execution Guardrails

-   **Terminology & Cost Framing:** Never promise or guarantee "cost-reduction"
    or "reducing expenditure." Always frame recommendations using the
    terminology **"optimizing your bill"** or **"improving cost-efficiency."**
-   **Explicit Scope Framing & Region Resolution:** Always state the target
    `project_id` and `region` at the very top of your response so the user
    immediately knows the exact scope being evaluated. Follow this 3-tier
    resolution hierarchy:
    1.  *Explicit Region:* Use the region specified in the user's prompt (e.g.,
        `europe-west1`).
    2.  *Contextual Region:* Resolve the region from the specific dataset or
        resource mentioned in the context.
    3.  *Unspecified Fallback:* Default to `us` / `region-us`, explicitly state
        that `us` was assumed as the default, and instruct the user to
        substitute their region if their resources reside elsewhere. *Region
        Formatting:* In Cloud Console deep links, use the region identifier
        directly (e.g., `region=us`, `region=europe-west1`). In SQL queries
        against `INFORMATION_SCHEMA`, use the regional dataset qualifier (e.g.,
        `region-us`, `region-europe-west1`).
-   **Zero-Row Result Guard:** If querying `TABLE_STORAGE` with `WHERE
    table_schema = '{dataset_id}'` returns 0 rows, do not proceed with an empty
    or zero-usage evaluation. Treat this as an indicator that the dataset may
    reside in a different region or have no native tables; stop and prompt the
    user to confirm the dataset's regional location.
-   **Populate Concrete Parameters:** When generating URLs and SQL queries,
    always substitute known `project_id` and `region` values directly into the
    code and links. Never leave literal `{project_id}` or `{location}`
    placeholders for the user to manually edit.
-   **No Autonomous Purchasing or Financial Mutations:** Never provide the user
    with executable scripts (e.g., `gcloud` or `bq` shell commands like `bq
    update --storage_billing_model=...`) designed to autonomously purchase
    annual commitments, alter edition tier bindings, or mutate storage billing
    models. Always guide the user to execute commitment purchases, reservation
    changes, and storage billing model updates manually via the Cloud Console
    UI.
references/
attribution.md 1.9 KB
# Usage Attribution

**MUST READ**: Before executing any `gcloud`, REST API, or MCP command with
this skill, follow these usage attribution instructions. Tag every command you
execute directly in the terminal so usage can be attributed. The tag identifies
only the skill and its version; it carries no user data.

-   **`gcloud` CLI Commands**: Prefix every `gcloud` invocation, whatever the
    subcommand, with the metrics environment variable. Set it inline on each
    command because shell state may not persist between commands:

    ```bash
    CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:bigquery-optimization)" \
    gcloud <command> [flags]
    ```

    Do not use `gcloud config set` for this: it would persist beyond the current
    task and mislabel unrelated usage.

-   **Direct HTTP, REST, and MCP Requests**: On direct HTTP calls to Google
    Cloud APIs (for example with `curl`) or HTTP requests to a remote MCP
    server, include `agent-skills/1.0 (skill:bigquery-optimization)` in the `User-Agent`
    header. If a `User-Agent` header is already specified, append this string to
    the end of it rather than overwriting existing `User-Agent` data — the
    collection pipeline parses the `agent-skills/<version>` and `skill:<name>`
    tokens, so any rewording breaks attribution:

    ```
    User-Agent: <existing_user_agent> agent-skills/1.0 (skill:bigquery-optimization)
    ```

-   **Constraint for Generated Code**: The tracking prefix is strictly for
    commands you execute directly in the terminal. Do NOT include this tracking
    prefix in generated scripts, Terraform templates, or code provided to the
    user for their own repositories.

-   **User Opt-Out**: If the user asks to disable or remove tracking or
    attribution tags, omit the `CLOUDSDK_METRICS_REQUEST_ATTRIBUTION` variable
    and custom `User-Agent` suffix from all commands.
bi_engine.md 7.3 KB
# BI Engine Acceleration Strategy

Architectural guidelines, eligibility constraints, and remediation workflows for
accelerating BI dashboard queries using BigQuery BI Engine.

## Table of Contents

-   [1. When to Propose BI Engine vs. Materialized Views](#1-when-to-propose-bi-engine-vs-materialized-views)
    (Lines 19-43)
-   [2. BI Engine Capacity & Preferred Tables](#2-bi-engine-capacity-preferred-tables)
    (Lines 45-61)
-   [3. Limitations & Fallback Causes (`PARTIAL` or `DISABLED`)](#3-limitations-fallback-causes-partial-or-disabled)
    (Lines 63-86)
-   [4. Remediating BI Engine Fallback with Materialized Views](#4-remediating-bi-engine-fallback-with-materialized-views)
    (Lines 88-110)
-   [5. Telemetry & Data Retrieval Reference](#5-telemetry-data-retrieval-reference)
    (Lines 112-126)

## 1. When to Propose BI Engine vs. Materialized Views

Use BI Engine and Materialized Views together or independently depending on the
bottleneck:

<!-- mdformat off -->
| Dimension | BigQuery BI Engine | Materialized Views (`CREATE MATERIALIZED VIEW`) | Combined (BI Engine + Materialized View) |
| :--- | :--- | :--- | :--- |
| **Primary Goal** | Accelerate BI dashboard queries from tools such as Looker, Data Studio (formerly Looker Studio), or Tableau. | Precompute and store aggregated results (such as `SUM` and `COUNT`) for queries that repeatedly aggregate large base tables. | Accelerate dashboards over a materialized view that pre-joins or pre-aggregates the data, so the same joins are not performed for each query. |
| **Mechanism** | In-memory analysis service that caches only the queried parts of columns and partitions. | BigQuery automatically adds incremental base-table changes to the view; smart tuning can reroute eligible base-table queries to it. | The materialized view joins and flattens (or pre-aggregates) the data, and BI Engine accelerates queries to the view. |
<!-- mdformat on -->

**Decision Rule:**

*   **Propose BI Engine** when users analyze data with BI tools (such as Looker,
    Data Studio, or Tableau), or when a subset of tables is queried more
    frequently or backs high-visibility dashboards (designate those tables as
    preferred tables).
*   **Propose a Materialized View** when queries repeatedly aggregate or join
    large base tables.
*   **Propose Both Together** when dashboards repeatedly join or aggregate large
    tables: use a materialized view to pre-join or pre-aggregate the data, and
    mark the view and its base tables as preferred tables. If the dashboard only
    displays recent data, also partition the tables by time so that only the
    latest partitions are loaded into memory.

## 2. BI Engine Capacity & Preferred Tables

*   **Capacity & Cost:** You incur costs for the reservation that you create for
    BI Engine capacity.
*   **Configuring BI Engine Reservations & Preferred Tables:**
    *   Never execute CLI scripts to purchase or mutate BI Engine capacity
        reservations autonomously. Guide the user to configure BI Engine
        capacity or **Preferred Tables** in the Google Cloud Console under
        **BigQuery** > **Administration** > **BI Engine**:
        `https://console.cloud.google.com/bigquery/admin/bi-engine?project={project_id}`
    *   **Preferred Tables:** If a subset of tables is queried more frequently
        or backs high-visibility dashboards, designate those tables as preferred
        tables. Queries to all other tables use regular BigQuery slots. Queries
        that access multiple tables (such as a `JOIN`) are only accelerated if
        all tables in the query are in the preferred tables list, and queries to
        materialized views are only accelerated if both the materialized views
        and their base tables are in the preferred tables list.

## 3. Limitations & Fallback Causes (`PARTIAL` or `DISABLED`)

When the project is configured to use BI Engine, `INFORMATION_SCHEMA.JOBS`
reports each query's acceleration status in
`bi_engine_statistics.bi_engine_mode` (`FULL`, `PARTIAL`, or `DISABLED`) and
`bi_engine_statistics.acceleration_mode` (for example, `FULL_INPUT` when all of
the query inputs were accelerated, or `FULL_QUERY` when all of the query was
accelerated). For `PARTIAL` or `DISABLED`,
`bi_engine_statistics.bi_engine_reasons` (`code` and `message`) explains why.
Query stages that BI Engine can't accelerate fall back to standard BigQuery
execution slots without failing the query. Documented limitations include:

*   **Join Limits:** BI Engine accelerates leaf-level subqueries with `INNER`
    and `LEFT OUTER` joins where a large fact table is joined with up to four
    smaller dimension tables. Each dimension table must have fewer than 5
    million rows and be 5 GiB or less (unpartitioned tables) or have referenced
    partitions of 1 GiB or less (partitioned tables).
*   **Unsupported Features:** BI Engine acceleration isn't available for:
    *   Queries that reference wildcard tables
    *   External tables, including BigLake tables
    *   JavaScript UDFs and remote functions
    *   Row-level security
    *   Queries that use `SEARCH` or `VECTOR_SEARCH` functions, or are optimized
        by search indexes or vector indexes

## 4. Remediating BI Engine Fallback with Materialized Views

When diagnostic telemetry (`bi_engine_statistics`) shows a high rate of
`PARTIAL` or `DISABLED` queries on a dashboard workload:

1.  **Inspect `bi_engine_reasons`:** Group `INFORMATION_SCHEMA.JOBS_BY_PROJECT`
    by `bi_engine_statistics.bi_engine_mode` and
    `UNNEST(bi_engine_statistics.bi_engine_reasons)` to identify the exact
    reason code (such as `INPUT_TOO_LARGE`, `UNSUPPORTED_SQL_TEXT`,
    `TABLE_EXCLUDED`, or `INSUFFICIENT_RESERVATION`).
2.  **Offload Heavy Aggregations & Joins to a Materialized View:** If dashboard
    queries repeatedly aggregate or join large base tables:
    *   Create a partitioned, clustered materialized view (see
        [materialized_views.md](materialized_views.md)) that pre-aggregates the
        dashboard dimensions and measures (such as `SUM` and `COUNT`).
    *   Smart tuning can rewrite eligible queries against the base tables to
        read the materialized view. If you use preferred tables, add both the
        materialized view and its base tables so that queries to the view can be
        accelerated.
3.  **Prune Scanned Partitions:** If the dashboard only displays recent data,
    partition the base tables by time and make sure dashboard queries filter on
    the partitioning column, so that only the latest partitions are loaded into
    memory.

## 5. Telemetry & Data Retrieval Reference

If the `bigquery-observability` skill is available in your workspace, refer to
its shared telemetry references for canonical query templates and schema
dictionaries. All architectural rules, eligibility limits, and remediation
workflows are self-contained within this guide.

*   **BI Engine Acceleration Usage & Fallback Reasons:** See the
    `bigquery-observability` skill (`references/job_performance_queries.md`,
    section "BI Engine Acceleration Usage") to query
    `bi_engine_statistics.bi_engine_mode` and
    `UNNEST(bi_engine_statistics.bi_engine_reasons)`.
*   **Jobs Schema (`bi_engine_statistics`):** See the `bigquery-observability`
    skill (`references/schema_compute.md`, section "1. Jobs & Compute Telemetry
    Views") for `INFORMATION_SCHEMA.JOBS` column definitions.
capacity_planning_editions.md 7.0 KB
# Compute Capacity Planning (Editions Migration & Rightsizing)

Guidelines for Org Admins and billing owners on evaluating On-Demand to Edition
migrations, as well as rightsizing active Edition reservations and commitments.

## Table of Contents

-   [Framing & Guardrails](#framing-guardrails) (Lines 17-35)
-   [1. Unified Slot Estimator Engine](#1-unified-slot-estimator-engine) (Lines 37-55)
-   [2. On-Demand to Editions Migration](#2-on-demand-to-editions-migration) (Lines 57-94)
    -   [Slot Estimator Migration Deep Links](#slot-estimator-migration-deep-links) (Lines 63-77)
    -   [Navigation & Workload Profiling](#navigation-workload-profiling) (Lines 79-94)
-   [3. Existing Edition Capacity Rightsizing](#3-existing-edition-capacity-rightsizing) (Lines 96-138)
    -   [Slot Estimator Rightsizing Deep Links](#slot-estimator-rightsizing-deep-links) (Lines 102-114)
    -   [Edition-Level Rightsizing Decision Playbook](#edition-level-rightsizing-decision-playbook) (Lines 116-138)

## Framing & Guardrails

When discussing cost or capacity optimizations, adhere to these central rubrics:

-   **Terminology & Framing:** Never promise or guarantee "cost-reduction."
    Always use the terminology **"optimizing your bill"** or **"improving
    cost-efficiency."**
-   **No Manual ROI Calculations:** Do not attempt manual mathematical formulas
    or spreadsheet-style ROI calculations to estimate Edition costs. BigQuery's
    built-in **Slot Estimator** UI simulates historical workloads with
    fine-grained precision. Always direct the user to the UI deep links and
    diagnostic queries.
-   **Direct Deep Links & Parameter Formatting:** Always populate concrete
    `project_id` and `region` parameters directly into Cloud Console deep links.
    In Cloud Console URLs, use the bare region identifier (e.g., `region=us`,
    `region=europe-west1`), omitting any `region-` prefix.
-   **No Autonomous Purchasing:** Guide the user to execute commitment and
    reservation changes manually in the Cloud Console. Never output executable
    purchase scripts (`gcloud`, `bq`).

## 1. Unified Slot Estimator Engine

The underlying mathematical mechanism of the Slot Estimator is **identical**
across both On-Demand migrations and existing Edition rightsizing:

-   **30-Day Workload Ingestion:** The engine analyzes up to 30 days of
    historical workload telemetry. For On-Demand, it models bytes billed and
    processed into equivalent slot demand; for Editions, it reads historical
    slot utilization per reservation.
-   **Performance Continuity:** The recommender assumes **no performance
    degradation**. It sets the combined recommended capacity (Baseline
    Commitment + Autoscale Max) to cover the observed **P99 slot demand** over
    the 30-day period.
-   **Autoscaler Simulation:** The engine simulates the autoscaler across each
    discrete time unit, testing every combination of baseline and autoscale
    limits that sum up to that P99 usage.
-   **Cost-Optimization:** Among all viable combinations that satisfy the P99
    performance target, the UI isolates and presents the single lowest-cost
    commitment and autoscaling configuration.

## 2. On-Demand to Editions Migration

Use when a project is currently on On-Demand billing and wants to evaluate
whether migrating to Editions (Standard, Enterprise, Enterprise Plus) improves
cost-efficiency.

### Slot Estimator Migration Deep Links

Provide the direct deep link with `source=EDITION_UNSPECIFIED`:

-   **Project-Level On-Demand Recommendations:**

    ```text
    https://console.cloud.google.com/bigquery/admin/reservations;region={region}/slot-estimator;source=EDITION_UNSPECIFIED;resourceType=PROJECT;resource={project_id}?project={project_id}
    ```

-   **Organization-Level On-Demand Recommendations:**

    ```text
    https://console.cloud.google.com/bigquery/admin/reservations;region={region}/slot-estimator;source=EDITION_UNSPECIFIED;resourceType=ORGANIZATION;resource={project_id}?project={project_id}
    ```

### Navigation & Workload Profiling

1.  Instruct the user to navigate to the **Slot Estimator** tab in the Capacity
    Management UI.
2.  Select **On-Demand** as the source from the selection panel.
3.  Review the **Cost-Optimized Recommendations** and the **Slot Usage Chart**,
    comparing Pay-As-You-Go against 1-year and 3-year capacity commitments.
4.  **Workload Profiling Strategy:**
    -   *Steady Baseline Workloads:* Workloads with flat, continuous slot demand
        throughout the day (e.g., constantly utilizing 400 slots). These are
        prime candidates for Edition commitments (1-Year or 3-Year CUDs) to
        maximize cost-efficiency (~40% discount).
    -   *Spiky Workloads:* Workloads requiring zero or few slots for most hours
        with sharp bursts. These benefit from low baseline allocations and
        dynamic autoscaling, but require conservative autoscaling caps to avoid
        unexpected burst costs.

## 3. Existing Edition Capacity Rightsizing

Use when an organization is already running on BigQuery Editions and wants to
audit active Edition capacity, right-size commitment purchases (CUDs), and
eliminate uncovered baseline PAYG waste.

### Slot Estimator Rightsizing Deep Links

Provide the direct deep link targeting the specific edition:

-   **Edition Rightsizing Recommendations:**

    ```text
    https://console.cloud.google.com/bigquery/admin/reservations;region={region}/slot-estimator;source={edition}?project={admin_project_id}
    ```

    *(Where `{edition}` is `ENTERPRISE` or `ENTERPRISE_PLUS`; Standard Edition
    does not support commitments and does not generate recommendations in the
    Slot Estimator)*

### Edition-Level Rightsizing Decision Playbook

1.  **Eliminate Uncovered Baseline PAYG Slots:**
    -   *Issue:* Total baseline slots configured across reservations in an
        Edition exceed active capacity commitments (`total_baseline_slots >
        committed_slots`). The uncovered baseline slots are billed 24/7 at
        standard Pay-As-You-Go (PAYG) rates.
    -   *Action:* Purchase 1-year or 3-year Capacity Commitments at the Edition
        level to cover the baseline capacity gap at discounted rates (~40%
        discount).
2.  **Right-Size Total Edition Commitments to Steady Baseline:**
    -   *Issue:* Commitments are purchased and managed at the Edition level, but
        the aggregate steady-state slot demand across all reservations in the
        Edition may have evolved.
    -   *Action:* Use the Slot Estimator to align 1-Year/3-Year commitments with
        the aggregate continuous baseline floor of the Edition, allowing dynamic
        autoscaling to absorb variable query demand above that floor.
3.  **Audit Excess Commitment Over-Provisioning:**
    -   *Issue:* Purchasing commitments that exceed aggregate slot utilization
        across the Edition results in paying for unused committed capacity.
    -   *Action:* Review the Slot Estimator's 30-day historical usage chart for
        the Edition to ensure commitment renewals and purchases do not exceed
        the true steady-state demand floor.
materialized_views.md 4.9 KB
# Materialized Views

Guidance for deciding when to propose a BigQuery materialized view and how to
write the `CREATE MATERIALIZED VIEW` statement. Propose the DDL to the user and
let them run it; never run it yourself.

## Table of Contents

-   [When to Propose a Materialized View](#when-to-propose-a-materialized-view)
    (Lines 18-24)
-   [Smart Tuning Requirements](#smart-tuning-requirements) (Lines 26-49)
-   [Partition Alignment, Clustering & Proposing the DDL](#partition-alignment-clustering-proposing-the-ddl)
    (Lines 51-87)
-   [Verifying the View](#verifying-the-view) (Lines 89-97)
-   [Telemetry & Data Retrieval Reference](#telemetry-data-retrieval-reference)
    (Lines 99-111)

## When to Propose a Materialized View

Propose a materialized view when queries repeatedly run the same aggregations,
filters, or joins over large base tables (for example, dashboards that query the
same summary metrics). A materialized view precomputes and stores aggregated
results and automatically combines them with incremental changes in the base
tables.

## Smart Tuning Requirements

BigQuery automatically rewrites queries against the base tables to read a
materialized view (smart tuning), so users don't need to change their queries. A
query is rewritten only if the view:

*   Belongs to the same project as one of its base tables or the project that
    the query runs in.
*   Uses the same set of base tables as the query.
*   Includes all columns that the query reads. For example, a query that reads a
    column the view doesn't include is not rewritten. If the view outputs
    `CAST(sold_datetime AS DATE)`, a query that filters on `sold_datetime`
    itself is not rewritten either.
*   Includes all rows that the query reads. For example, a query is not
    rewritten if it reads dates outside the view's `WHERE` range, or adds a more
    restrictive filter on a column that the view filters on but doesn't output.

Smart tuning isn't supported for materialized views that:

*   Reference logical views.
*   Use `UNION ALL` or `LEFT OUTER JOIN`.
*   Are non-incremental (`allow_non_incremental_definition = true`). Users must
    query these views directly.
*   Reference tables with change data capture (CDC) enabled.

## Partition Alignment, Clustering & Proposing the DDL

Base the view definition on the query patterns against the base tables, so that
it serves a broad set of queries rather than one query. For example, if users
often filter on `user_id` or `department`, group by (and optionally cluster on)
those columns instead of adding a filter such as `user_id = 123` to the view.
For date filters, omit narrow date filters or use a date range that covers all
ranges the queries read.

For partitioning and clustering:

*   **Partition alignment:** If the base table is partitioned, partition the
    view on the same partitioning column to reduce refresh and query cost. For
    time-based partitioning, the granularity must match the base table, and a
    truncation function applied to the partitioning column must be at least as
    granular as the base table's partitioning. For integer-range partitioning,
    the range must match exactly. A view over a non-partitioned base table can't
    be partitioned.
*   **Clustering:** Cluster on output columns that queries filter on. Aggregate
    output columns can't be clustering columns.

For a base table partitioned by `DATE(event_ts)`:

```sql
CREATE MATERIALIZED VIEW `{project_id}.{dataset_id}.{view_name}`
  PARTITION BY DATE(event_day)
  CLUSTER BY service_name
AS (
  SELECT
    TIMESTAMP_TRUNC(event_ts, DAY) AS event_day,
    service_name,
    COUNT(*) AS request_count,
    SUM(bytes_sent) AS total_bytes_sent
  FROM `{project_id}.{dataset_id}.{table_id}`
  GROUP BY event_day, service_name
);
```

## Verifying the View

Check that the view appears in `materialized_view_statistics` with `chosen` set
to `TRUE`, or that the query plan contains a `READ {view_name}` step. If
`chosen` is `FALSE`, read `rejected_reason` (for example, `NO_DATA` means the
view hasn't refreshed yet, and `COST` means another source was estimated to be
cheaper). If the view is not listed at all, the query shape doesn't match the
view; compare it with [Smart Tuning Requirements](#smart-tuning-requirements).
If many views are considered, the list might be incomplete.

## Telemetry & Data Retrieval Reference

If the `bigquery-observability` skill is available in your workspace, refer to
its telemetry references for the query templates. All decision rules and DDL
templates are self-contained within this guide. Without that skill, check
`materialized_view_statistics` in the region-qualified `INFORMATION_SCHEMA.JOBS`
view.

*   **Rewrite Usage:** See the `bigquery-observability` skill
    (`references/job_performance_queries.md`, section "Materialized View Rewrite
    Usage"). For a single job, `bq show --format=prettyjson
    --location={location} -j {project_id}:{job_id}` returns
    `statistics.query.materializedViewStatistics`.
search_indexes.md 4.1 KB
# Search Indexes

Guidance for deciding when to propose a BigQuery search index and how to write
the `CREATE SEARCH INDEX` statement. Propose the DDL to the user and let them
run it; never run it yourself.

## Table of Contents

-   [When to Propose a Search Index](#when-to-propose-a-search-index) (Lines
    16-34)
-   [Proposing the DDL](#proposing-the-ddl) (Lines 36-71)
-   [Verifying the Index](#verifying-the-index) (Lines 73-83)
-   [Telemetry & Data Retrieval Reference](#telemetry-data-retrieval-reference)
    (Lines 85-100)

## When to Propose a Search Index

Propose a search index when all of the following are true:

*   Queries repeatedly look up specific values (for example, an IP address, an
    ID, or an error code) in `STRING` or `JSON` data. Searches work best when
    they return few results.
*   The table is at least 10 GB. Search indexes are designed for large tables:
    an index on a table smaller than 10 GB is not populated, and queries don't
    use it (`IndexUnusedReason` code `BASE_TABLE_TOO_SMALL`).
*   The lookups use the `SEARCH` function, or can be rewritten to use `SEARCH`.
    Because `SEARCH` matches tokens rather than substrings, its results can
    differ from `REGEXP_CONTAINS` or `LIKE '%term%'` (wrap exact tokens
    containing delimiters in backticks, such as `` '`req-7f3a9c`' ``, and
    confirm with the user). For `REGEXP_CONTAINS` or `LIKE '%term%'` filters,
    propose the index together with the `SEARCH` rewrite from the rule "Use
    SEARCH on columns with a search index" in
    [sql_optimization.md](sql_optimization.md), to apply once the index's
    `coverage_percentage` is above 0.

## Proposing the DDL

Index only the `STRING` or `JSON` columns that queries search:

```sql
CREATE
  SEARCH INDEX {index_name}
ON `{project_id}.{dataset_id}.{table_id}`({column_1}, {column_2});
```

Or index all `STRING` and `JSON` data in the table:

```sql
CREATE
  SEARCH INDEX {index_name}
ON `{project_id}.{dataset_id}.{table_id}`(ALL COLUMNS);
```

Analyzer option (`analyzer`):

*   `LOG_ANALYZER` (default) works well for machine-generated logs and has rules
    for tokens such as IP addresses and emails. `NO_OP_ANALYZER` matches
    pre-processed data exactly. `PATTERN_ANALYZER` extracts tokens with a
    regular expression. With a non-default analyzer, queries must pass the same
    analyzer to `SEARCH` (for example, `SEARCH(email, 'kim', analyzer =>
    'NO_OP_ANALYZER')`).

For example:

```sql
CREATE
  SEARCH INDEX {index_name}
ON
  `{project_id}.{dataset_id}.{table_id}`(ALL COLUMNS)
  OPTIONS (analyzer = 'NO_OP_ANALYZER');
```

## Verifying the Index

Every search index proposal must tell the user how to verify it, in two steps:

1.  **Coverage, before relying on the index:** Check that `index_status` is
    `ACTIVE` and `coverage_percentage` is above 0. A `coverage_percentage` of 0
    means the index is not usable in a `SEARCH` query, even if some data has
    already been indexed.
2.  **Usage, after queries run:** Check that `index_usage_mode` is `FULLY_USED`
    or `PARTIALLY_USED`. For `UNUSED` or `PARTIALLY_USED`, read the
    `index_unused_reasons` codes (for example, `BASE_TABLE_TOO_SMALL`).

## Telemetry & Data Retrieval Reference

If the `bigquery-observability` skill is available in your workspace, refer to
its telemetry references for the query templates. All decision rules and DDL
templates are self-contained within this guide. Without that skill, check
`index_status` and `coverage_percentage` in the dataset-qualified
`INFORMATION_SCHEMA.SEARCH_INDEXES` view, and `search_statistics` in the
region-qualified `INFORMATION_SCHEMA.JOBS` view.

*   **Index Coverage:** See the `bigquery-observability` skill
    (`references/storage_footprints.md`, section "Search Index Coverage Query").
*   **Index Usage:** See the `bigquery-observability` skill
    (`references/job_performance_queries.md`, section "Search Index Usage") for
    `search_statistics.index_usage_mode` and `index_unused_reasons`. For a
    single job, `bq show --format=prettyjson --location={location} -j
    {project_id}:{job_id}` returns `statistics.query.searchStatistics`.
sql_optimization.md 23.5 KB
# BigQuery SQL Optimization

Guidance for optimizing the user's SQL by applying a list of optimization rules.
Apply any of the rules listed below to the provided SQL. If none of the rules
apply, tell the user that their query is already optimal. Only consult the list
of rules in the subsections in this file.

> [!TIP] Always include a **"Summary of Optimizations"** section listing only
> the optimizations applied.

## Table of Contents

-   [SQL optimization rules for reducing slot-time](#sql-optimization-rules-for-reducing-slot-time) (Lines 33-569)
    -   [Materialize a CTE with temporary tables](#materialize-a-cte-with-temporary-tables) (Lines 35-75)
    -   [Order multiple temporary tables or variables in reference order](#order-multiple-temporary-tables-or-variables-in-reference-order) (Lines 77-142)
    -   [Add DISTINCT to semijoin subqueries](#add-distinct-to-semijoin-subqueries) (Lines 144-190)
    -   [Replace REGEXP_CONTAINS with LIKE](#replace-regexp_contains-with-like) (Lines 192-210)
    -   [Use SEARCH on columns with a search index](#use-search-on-columns-with-a-search-index) (Lines 212-260)
    -   [In a WHERE clause, use a BETWEEN expression instead of the EXTRACT function](#in-a-where-clause-use-a-between-expression-instead-of-the-extract-function) (Lines 262-295)
    -   [Add a LIMIT clause to an ORDER BY clause](#add-a-limit-clause-to-an-order-by-clause) (Lines 297-327)
    -   [Remove an ORDER BY clause from a CREATE TABLE statement](#remove-an-order-by-clause-from-a-create-table-statement) (Lines 329-359)
    -   [Compare date columns to DATE literals, not string casts](#compare-date-columns-to-date-literals-not-string-casts) (Lines 361-391)
    -   [Add a null filter to a NOT IN subquery](#add-a-null-filter-to-a-not-in-subquery) (Lines 393-422)
    -   [Replace a WHERE IN OR IN clause with LEFT JOINs](#replace-a-where-in-or-in-clause-with-left-joins) (Lines 424-460)
    -   [Replace exact aggregates with approximate aggregates](#replace-exact-aggregates-with-approximate-aggregates) (Lines 462-491)
    -   [Pre-aggregate join inputs before joining](#pre-aggregate-join-inputs-before-joining) (Lines 493-569)
-   [SQL optimization rules for reducing amount of data](#sql-optimization-rules-for-reducing-amount-of-data) (Lines 571-818)
    -   [Replace `SELECT *` with a specific column list](#replace-select-with-a-specific-column-list) (Lines 573-610)
    -   [Check the query filters on the partitioned column](#check-the-query-filters-on-the-partitioned-column) (Lines 612-818)
        -   [Fetching table schemas from BigQuery](#fetching-table-schemas-from-bigquery) (Lines 774-802)
        -   [Validating a rewrite with a dry run](#validating-a-rewrite-with-a-dry-run) (Lines 804-818)

## SQL optimization rules for reducing slot-time

### Materialize a CTE with temporary tables

If there is a CTE clause that is referenced multiple times, suggest
materializing it into a temporary table by wrapping the CTE clause in a `CREATE
TEMP TABLE AS` statement.

Rationale: CTE clauses are evaluated every time a query references them;
materializing a CTE into a temporary table means that it will only be evaluated
once.

Here is an example of a query where multiple CTEs are referenced multiple times:

```sql
WITH t1 AS (SELECT a0 FROM a),
     t2 AS (SELECT x.a0 FROM t1, t1 x),
     t3 AS (SELECT x.a0 FROM t2, t2 x),
     t4 AS (SELECT x.a0 FROM t3, t3 x)
SELECT
  a0,
  COUNT(*)
FROM
  t4
GROUP BY
  1;
```

Here is how the rewritten query should look:

```sql
CREATE TEMP TABLE t1 AS (SELECT a0 FROM a);
CREATE TEMP TABLE t2 AS (SELECT x.a0 FROM t1, t1 x);
CREATE TEMP TABLE t3 AS (SELECT x.a0 FROM t2, t2 x);
CREATE TEMP TABLE t4 AS (SELECT x.a0 FROM t3, t3 x);
SELECT
  a0,
  COUNT(*)
FROM
  t4
GROUP BY
  1;
```

### Order multiple temporary tables or variables in reference order

When applying the rules for materializing CTEs into temporary tables (see
subsection "Materialize a CTE with temporary tables") or declaring variables
(see rule 3.b. in the subsection "Check the query filters on the partitioned
column"), order them in the order that they are referenced in the query.
Temporary tables and variables must come before other temporary tables or
variables that reference them.

Example of a query with a temporary table and a variable that is out of order:

```sql
DECLARE last_order_date DEFAULT (
  SELECT
    max(date)
  FROM
    quantity_sold_per_day
);

CREATE TEMP TABLE quantity_sold_per_day AS (
  SELECT
    EXTRACT(DATE from timestamp) AS date,
    SUM(quantity) as total_quantity
  FROM
    orders
  GROUP BY 1
);

SELECT
  timestamp,
  order_id,
  quantity
FROM
  orders
WHERE
  timestamp >= last_order_date;
```

Here is the corrected order of the temporary table and variable:

```sql
CREATE TEMP TABLE quantity_sold_per_day AS (
  SELECT
    EXTRACT(DATE from timestamp) AS date,
    SUM(quantity) as total_quantity
  FROM
    orders
  GROUP BY 1
);

DECLARE last_order_date DEFAULT (
  SELECT
    max(date)
  FROM
    quantity_sold_per_day
);

SELECT
  timestamp,
  order_id,
  quantity
FROM
  orders
WHERE
  timestamp >= last_order_date;
```

### Add DISTINCT to semijoin subqueries

If the query contains a semijoin, rewrite the subquery to have a DISTINCT clause
only if the subquery does not have a GROUP BY clause. If the subquery has a
GROUP BY clause, then the subquery should remain as is. If the subquery does not
have a GROUP BY clause, then the subquery should be rewritten to have a DISTINCT
clause.

Rationale: `DISTINCT` in the semijoin subquery reduces the amount of data to
check for in the `IN` clause.

Here is an example of a query with a semijoin whose subquery does not have a
GROUP BY clause:

```sql
SELECT
  t1.a0
FROM
  test.a t1
WHERE
  t1.a2 IN (SELECT t2.a2 FROM test.a t2);
```

Here is the query rewritten with a DISTINCT clause:

```sql
SELECT
  t1.a0
FROM
  test.a AS t1
WHERE
  t1.a2 IN (SELECT DISTINCT t2.a2 FROM test.a t2);
```

Here is an example of a query with a semijoin whose subquery has a GROUP BY
clause and should not be rewritten:

```sql
SELECT
  t1.a0
FROM
  test.a t1
WHERE
  t1.a2 IN (SELECT t2.a2, count(*) FROM test.a t2 group by 1);
```

This query should not be rewritten since the subquery has an aggregation.

### Replace REGEXP_CONTAINS with LIKE

If the query contains the function `REGEXP_CONTAINS` where the regular
expression uses wildcards, rewrite the query to use the `LIKE` operator instead.

Rationale: `LIKE` is more performant than `REGEXP_CONTAINS`.

Examples of valid rewrites:

*   `REGEXP_CONTAINS(a, '.*abc.*')` should be rewritten as `a LIKE '%abc%'`
*   `REGEXP_CONTAINS(a, '^abc.*')` should be rewritten as `a LIKE 'abc%'`
*   `REGEXP_CONTAINS(a, '.*abc$')` should be rewritten as `a LIKE '%abc'`
*   `REGEXP_CONTAINS(a, '.*abc.*def.*')` should be rewritten as `a LIKE
    '%abc%def%'`

Example of where `REGEXP_CONTAINS` should not be rewritten:

*   `REGEXP_CONTAINS(a, 'abc')` should not be rewritten as `a LIKE '%abc%'`
    since the query does not contain any wildcards.

### Use SEARCH on columns with a search index

If the query filters a column with `REGEXP_CONTAINS` or `LIKE '%term%'` and the
column is covered by an `ACTIVE` search index with a `coverage_percentage` above
0 (the user confirms, or `INFORMATION_SCHEMA.SEARCH_INDEXES` shows the column or
`ALL COLUMNS` in `ddl`), suggest rewriting the filter to use the `SEARCH`
function. If no index exists, propose the rewrite only together with an index
proposal, to apply once coverage is above 0. Do not rewrite `=`, `IN`, `LIKE
'prefix%'`, `STARTS_WITH`, or `ENDS_WITH` comparisons with string literals;
BigQuery can already use the search index for them.

`SEARCH` matches tokens, not substrings. With the default `LOG_ANALYZER` it is
case-insensitive, and `SEARCH(a, '192.0.2.1')` matches any row that contains
the tokens `192`, `0`, `2`, and `1` in any order; enclose the term in backticks
for an exact match. If the index uses a non-default analyzer, pass the same
analyzer to `SEARCH`. Because the results can differ from the original filter,
propose it and wait for the user to confirm before applying; do not include it
in an otherwise-automatic rewrite. For when to create an index, see
[search_indexes.md](search_indexes.md).

Rationale: A search index lets BigQuery skip base table data that doesn't
contain the search tokens, which reduces bytes processed and slot time. Savings
are largest when the matching rows are a small fraction of the table.

Here is an example of a query that filters an indexed column with `LIKE`:

```sql
SELECT
  Level,
  Source,
  Message
FROM
  my_dataset.Logs
WHERE
  Message LIKE '%94.60.64.181%';
```

Here is the rewritten query with `SEARCH`:

```sql
SELECT
  Level,
  Source,
  Message
FROM
  my_dataset.Logs
WHERE
  SEARCH(Message, '`94.60.64.181`');
```

### In a WHERE clause, use a BETWEEN expression instead of the EXTRACT function

If the column is a `DATE` type: rewrite filter expressions of the form
`EXTRACT(YEAR FROM date_column) = 2024` to `date_column BETWEEN '2024-01-01' AND
'2024-12-31'`.

If the column is a `TIMESTAMP` type: rewrite filter expressions of the form
`EXTRACT(YEAR FROM timestamp_column) = 2024` to `timestamp_column >= '2024-01-01
00:00:00' AND timestamp_column < '2025-01-01 00:00:00'`.

Rationale: BigQuery can statically evaluate `BETWEEN` expressions; it cannot
statically evaluate functions applied to columns.

Example of a query with a date filter expression:

```sql
SELECT
  t1.a0
FROM
  test.a AS t1
WHERE
  EXTRACT(YEAR FROM t1.a2) = 2024;
```

Here is the query rewritten with a date filter expression:

```sql
SELECT
  t1.a0
FROM
  test.a AS t1
WHERE
  t1.a2 BETWEEN '2024-01-01' AND '2024-12-31';
```

### Add a LIMIT clause to an ORDER BY clause

If a query has an `ORDER BY` clause without a `LIMIT` clause, suggest adding a
`LIMIT` clause.

Rationale: In vast majority of cases, users do not need the full results of an
`ORDER BY` clause; `LIMIT` improves the performance of the `ORDER BY` clause.

Example of a query with an `ORDER BY` clause without a `LIMIT` clause:

```sql
SELECT
  t1.a0
FROM
  test.a AS t1
ORDER BY
  t1.a2;
```

Here is the example query rewritten with a `LIMIT` clause:

```sql
SELECT
  t1.a0
FROM
  test.a AS t1
ORDER BY
  t1.a2
LIMIT
  1000;
```

### Remove an ORDER BY clause from a CREATE TABLE statement

If a query is a `CREATE TABLE` or `CREATE OR REPLACE TABLE` statement, remove an
`ORDER BY` clause if it has one.

Rationale: When writing to a table, BigQuery will order the data as needed,
making the `ORDER BY` unnecessary.

Here is an example of a query with a `CREATE OR REPLACE TABLE` statement with an
`ORDER BY` clause:

```sql
CREATE OR REPLACE TABLE test.a AS (
  SELECT
    t1.a0
  FROM
    test.b AS t1
  ORDER BY t1.a2
);
```

Here is the query rewritten with the `ORDER BY` clause removed:

```sql
CREATE OR REPLACE TABLE test.a AS (
  SELECT
    t1.a0
  FROM
    test.b AS t1
);
```

### Compare date columns to DATE literals, not string casts

Rewrite filter expressions of the form `CAST(date_column AS STRING) =
'2025-01-15'` to `date_column = DATE('2025-01-15')`.

Rationale: BigQuery can statically evaluate comparisons against the column
unless the column has a function applied to it.

Example of a query with a date filter expression that casts a `DATE` column to a
string:

```sql
SELECT
  t1.a0
FROM
  test.a AS t1
WHERE
  CAST(DATE(date_column) AS STRING) = '2025-01-15';
```

Here is the query rewritten with a date filter expression that does not cast the
`DATE` column but instead casts the string literal to a `DATE`:

```sql
SELECT
  t1.a0
FROM
  test.a AS t1
WHERE
  date_column = DATE('2025-01-15');
```

### Add a null filter to a NOT IN subquery

Rewrite subqueries within `NOT IN` clauses to add a `WHERE` clause that excludes
nulls.

Rationale: It allows BigQuery to use the more performant anti-hash join instead
of the slower left outer hash join.

Here is an example of a query with a subquery in a `NOT IN` clause:

```sql
SELECT
  t1.a0
FROM
  test.a AS t1
WHERE
  t1.a2 NOT IN (SELECT t2.a2 FROM test.b AS t2);
```

Here is the rewritten query that adds a `WHERE` clause to exclude nulls in the
`NOT IN` subquery:

```sql
SELECT
  t1.a0
FROM
  test.a AS t1
WHERE
  t1.a2 NOT IN (SELECT t2.a2 FROM test.b AS t2 WHERE t2.a2 IS NOT NULL);
```

### Replace a WHERE IN OR IN clause with LEFT JOINs

If the query contains a `WHERE ... IN (...) OR ... IN (...)` clause, which is an
expression that follows this pattern: `columnA IN (subqueryX) OR columnB in
(subqueryY)`, then rewrite the query to use `LEFT JOIN` clauses.

Rationale: `WHERE ... IN (...) OR ... IN (...)` uses a cross product join, which
can be significantly more expensive than `LEFT JOIN`s.

Example of a query with a `WHERE` clause that has two `IN` clauses:

```sql
SELECT
  t1.a0,
  t1.a1
FROM
  test.a AS t1
WHERE
  t1.a2 IN (SELECT t2.a2 FROM test.b AS t2)
  OR t1.a3 IN (SELECT t3.a3 FROM test.c AS t3);
```

Here is the rewritten query with `LEFT JOIN` clauses:

```sql
SELECT
  t1.a0,
  t1.a1
FROM
  test.a AS t1
LEFT JOIN (SELECT DISTINCT a2 FROM test.b) AS t2
  ON t1.a2 = t2.a2
LEFT JOIN (SELECT DISTINCT a3 FROM test.c) AS t3
  ON t1.a3 = t3.a3
WHERE
  t2.a2 IS NOT NULL OR t3.a3 IS NOT NULL;
```

### Replace exact aggregates with approximate aggregates

If the query contains the expression `COUNT(DISTINCT ...)`, suggest rewriting to
use `APPROX_COUNT_DISTINCT(...)`.

This changes exact counts to approximate ones. Propose it and wait for the user
to confirm before applying; do not include it in an otherwise-automatic rewrite.

Rationale: Approximate aggregates are significantly more efficient than exact
aggregates, however at the cost of precision. As a general rule of thumb, large
aggregations should use approximate aggregates, and small aggregations should
use exact aggregates.

Here is an example of a query with a `COUNT(DISTINCT ...)` expression:

```sql
SELECT
  COUNT(DISTINCT t1.a0)
FROM
  test.a AS t1;
```

Here is the rewritten query with `APPROX_COUNT_DISTINCT`:

```sql
SELECT
  APPROX_COUNT_DISTINCT(t1.a0)
FROM
  test.a AS t1;
```

### Pre-aggregate join inputs before joining

If a `WITH` CTE joins a detail table to a parent table without aggregating and
the outer query immediately aggregates (`GROUP BY`) that CTE's rows by the join
key, rewrite the CTE to pre-aggregate the detail table by the join key before
joining to the parent table in the outer query, and place the largest table
first (leftmost) in the `JOIN` clause. Only apply this rule when the query has a
`WITH` CTE that performs an unaggregated `JOIN` followed by an outer `GROUP BY`;
do not apply it to flat queries without a join CTE or to queries that already
aggregate in a semijoin (`WHERE ... IN (SELECT ... GROUP BY ...)`).

Rationale: Reducing data with `GROUP BY` before a `JOIN` avoids shuffling and
multiplying detail rows across the join stage (`records_written >>
records_read` and `shuffle_output_bytes_spilled > 0` in `job_stages`), reducing
both slot-time and shuffle memory usage. When diagnosing a Cartesian join
explosion, also inspect the `JOIN` clauses for unintentional `CROSS JOIN`s,
missing `ON` conditions, or non-selective join predicates (duplicate keys on
both sides), and filter out `NULL` or skewed dummy keys (e.g., `WHERE
customer_id IS NOT NULL AND customer_id != 'GUEST'`) before joining.

Here is an example of a query that joins `comments` and `users` before
aggregating:

```sql
WITH
  users_posts AS (
    SELECT
      u.display_name,
      u.reputation,
      c.score,
      c.text,
      c.user_id
    FROM
      `my_dataset.comments` AS c
    JOIN
      `my_dataset.users` AS u
      ON c.user_id = u.id
  )
SELECT
  display_name,
  reputation,
  AVG(score) AS avg_score,
  COUNT(text) AS comments_count
FROM
  users_posts
GROUP BY
  display_name,
  reputation,
  user_id;
```

Here is the rewritten query that pre-aggregates `comments` by `user_id` before
joining to `users`:

```sql
WITH
  comments_by_user AS (
    SELECT
      user_id,
      AVG(score) AS avg_score,
      COUNT(text) AS comments_count
    FROM
      `my_dataset.comments`
    GROUP BY
      user_id
  )
SELECT
  u.display_name,
  u.reputation,
  c.avg_score,
  c.comments_count
FROM
  comments_by_user AS c
JOIN
  `my_dataset.users` AS u
  ON c.user_id = u.id;
```

## SQL optimization rules for reducing amount of data

### Replace `SELECT *` with a specific column list

If the query contains a `SELECT *`, tell the user to rewrite to select only the
columns needed. Only suggest this for the top-level `SELECT` in the main query
or in `CREATE TEMP TABLE` statements. Do not suggest this for subqueries in
`WITH` and `WHERE` clauses.

Rationale: Selecting only the necessary columns reduces the amount of data that
BigQuery needs to read and process. `SELECT *` in subqueries do not necessarily
increase the amount of data read, as BigQuery can prune the columns in the
subquery.

Example of a query with a top-level `SELECT *` for which the user should specify
a column list:

```sql
SELECT
  *
FROM
  test;
```

Example of a query with a subquery that has `SELECT *`, which should not need to
be rewritten:

```sql
SELECT
  orders.order_id,
  SUM(orders.quantity) as total_quantity
FROM
  orders
WHERE EXISTS (
    SELECT *
    FROM line_items
    WHERE orders.order_id = line_items.order_id
  )
GROUP BY 1;
```

### Check the query filters on the partitioned column

Check the given query on how it filters (either a `WHERE` clause in a `SELECT`
statement or `ON` clause in a `JOIN` statement) on the partitioned column.

Steps to follow:

1.  Find all referred tables in `SELECT` or `JOIN` statements. If the query does
    not specify the project ID, use the project ID from the context.

    Example 1 where the referred tables follow the format `DATASET.TABLE` and do
    not specify the project ID:

    ```sql
    SELECT
      COUNT(o_orderkey)
    FROM
      my_dataset.orders
    INNER JOIN
      my_dataset.customers
      ON (o_custkey = c_custkey)
    ```

    Assuming that the project ID from the context is `my-project-id`, the
    referred tables in Example 1 are:

    -   `my-project-id.my_dataset.orders`
    -   `my-project-id.my_dataset.customers`

    Example 2 where the referred tables follow the format
    `PROJECT_ID.DATASET.TABLE`:

    ```sql
    SELECT
      COUNT(o_orderkey)
    FROM
      `my-project-id.my_dataset.orders`
    INNER JOIN
      `my-project-id.my_dataset.customers`
      ON (o_custkey = c_custkey)
    ```

    The referred tables in Example 2 are:

    -   `my-project-id.my_dataset.orders`
    -   `my-project-id.my_dataset.customers`

2.  Fetch the table schema from BigQuery for each referred table and get the
    partitioned column for each table if it exists.

    In the JSON output, use the field
    `partitionDefinition.partitionedColumn.field`. Note that this field is
    repeated, but in practice only one field is populated when the table is
    partitioned.

3.  For each table with a partitioned column, check the following rules:

    a. Ensure that the query contains a filter condition for the partitioned
    column for each table reference. If there is no filter condition for the
    partitioned column and the table has a partitioned column, tell the user.

    Rationale: If a table is partitioned, queries should leverage the
    partitioning to reduce the amount of data to read.

    Note that if the table's schema specifies that the partition filter is
    required (as specified in the field `requirePartitionFilter`), then no
    filter condition will cause the query to return an error.

    Example of query that does *not* have a filter condition on a partitioned
    column `o_orderdate` for table reference `my_dataset.orders`:

    ```sql
    SELECT
      COUNT(o_orderkey)
    FROM
      my_dataset.orders
    INNER JOIN
      my_dataset.customers
      ON (o_custkey = c_custkey)
    ```

    Example suggested improvement to show users:

    ```sql
    SELECT
      COUNT(o_orderkey)
    FROM
      my_dataset.orders
    INNER JOIN
      my_dataset.customers
      ON (o_custkey = c_custkey)
    WHERE
      -- Ask the user to provide the start and end dates.
      o_orderdate BETWEEN @start_date AND @end_date
    ```

    b. If the filter condition for the partitioned column is dynamic
    (specifically, a scalar subquery or a column-dependent aggregation), rewrite
    the query so that the filter condition is in a variable.

    Example of a query with a dynamic filter condition that is doing an
    aggregation on a partitioned column:

    ```sql
    SELECT o_orderstatus, o_orderdate
      FROM `my_dataset.orders`
    WHERE
      o_orderdate = (
        SELECT max(o_orderdate) FROM `my_dataset.orders`
      );
    ```

    Here is the query rewritten so that the filter condition is in a variable:

    ```sql
    DECLARE max_order_date DATE DEFAULT (
      SELECT max(o_orderdate) FROM `my_dataset.orders`
    );
    SELECT o_orderstatus, o_orderdate
    FROM `my_dataset.orders`
    WHERE
      o_orderdate = max_order_date;
    ```

    Note that the variable `max_order_date` still scans the entire table,
    however the full scan is still more efficient than the original query. If
    the table is configured with `require_partition_filter = true`, then the
    user needs to add an additional filter condition within the variable
    `max_order_date`.

    c. Isolate the partitioned column from unsupported functions and arithmetic
    expressions. BigQuery prunes partitions when the `WHERE` filter compares the
    partitioned column (or a documented pruning-supported built-in function on
    the partitioned column, such as `DATE(ts_col)`, `EXTRACT(DATE FROM ts_col)`,
    `CAST(ts_col AS DATE)`, `DATE_TRUNC`, or `TIMESTAMP_TRUNC` with constant
    arguments) against a constant expression. Wrapping the partitioned column in
    an unsupported function (such as `FORMAT_DATE` or `EXTRACT(MONTH FROM
    ts_col)`) or applying arithmetic to the partitioned column (such as
    `ts_col + INTERVAL 1 DAY > CURRENT_TIMESTAMP()`) prevents partition pruning.
    Rewrite the filter to isolate the partitioned column on one side of the
    comparison:

    ```sql
    -- Unpruned (arithmetic on the partitioned column):
    SELECT
      order_id,
      total_amount
    FROM
      `my_dataset.orders`
    WHERE
      order_timestamp + INTERVAL 1 DAY > CURRENT_TIMESTAMP();

    -- Rewritten to isolate the partitioned column for partition pruning:
    SELECT
      order_id,
      total_amount
    FROM
      `my_dataset.orders`
    WHERE
      order_timestamp > CURRENT_TIMESTAMP() - INTERVAL 1 DAY;
    ```

#### Fetching table schemas from BigQuery

Use the following shell command to fetch the table schema from BigQuery:

-   If the query specifies the project ID:

    ```bash
    bq show --format=prettyjson PROJECT_ID:DATASET.TABLE
    ```

    For example, given this table reference: `my_project:my_dataset.orders`, run
    the command:

    ```bash
    bq show --format=prettyjson my_project:my_dataset.orders
    ```

-   If the query does not specify the project ID:

    ```bash
    bq show --format=prettyjson DATASET.TABLE
    ```

    For example, given this table reference: `my_dataset.orders`, run the
    command:

    ```bash
    bq show --format=prettyjson my_dataset.orders
    ```

#### Validating a rewrite with a dry run

After rewriting a query to add partition filters or replace `SELECT *` with
explicit columns, instruct the user to validate the estimated bytes processed
before executing the query using a dry run:

```bash
bq query --use_legacy_sql=false --dry_run "{sql_query}"
```

A dry run validates SQL syntax and returns the deterministic
`totalBytesProcessed` estimate after partition pruning and column pruning
without running the query or incurring compute charges. Note that block-pruning
savings from clustered columns are determined dynamically during execution and
are not reflected in the dry-run upper bound.
storage_billing_models.md 6.2 KB
# Storage Billing Models: Logical vs. Physical Optimization

Guidance for evaluating whether a BigQuery dataset achieves better
cost-efficiency under `LOGICAL` or `PHYSICAL` storage billing.

## Table of Contents

-   [1. Evaluation Workflow](#1-evaluation-workflow) (Lines 17-81)
    -   [Step 1: Gather Target Metrics](#step-1-gather-target-metrics) (Lines 22-34)
    -   [Step 2: Calculate Cost Comparison](#step-2-calculate-cost-comparison) (Lines 36-61)
    -   [Step 3: Evaluate Decision Rules & Trade-offs](#step-3-evaluate-decision-rules-trade-offs) (Lines 63-81)
-   [2. Actionable Recommendations](#2-actionable-recommendations) (Lines 83-107)
    -   [If Currently on Logical Billing:](#if-currently-on-logical-billing) (Lines 88-97)
    -   [If Currently on Physical Billing:](#if-currently-on-physical-billing) (Lines 99-107)
-   [3. Critical Footguns](#3-critical-footguns) (Lines 109-129)

## 1. Evaluation Workflow

Follow this step-by-step workflow when a user inquires about switching storage
billing models:

### Step 1: Gather Target Metrics

Retrieve storage metrics from the regional `INFORMATION_SCHEMA.TABLE_STORAGE`
view for the target dataset.

-   **Scope:** Query ``
    `{project_id}`.`region-{location}`.INFORMATION_SCHEMA.TABLE_STORAGE``
    filtered by `table_schema = '{dataset_id}'`, `table_type = 'BASE TABLE'`,
    and non-zero storage (`total_physical_bytes + fail_safe_physical_bytes > 0`)
    to isolate billable native base tables.
-   **Inputs Required:** `active_logical_bytes`, `long_term_logical_bytes`,
    `active_physical_bytes`, `long_term_physical_bytes`,
    `time_travel_physical_bytes`, and `fail_safe_physical_bytes`.

### Step 2: Calculate Cost Comparison

Calculate the forecasted monthly costs for both models using regional or
contract unit rates:

```text
logical_cost  = (active_logical_gib * price_active_logical)
              + (long_term_logical_gib * price_long_term_logical)

physical_cost = (
                  (active_physical_gib + fail_safe_physical_gib)
                  * price_active_physical
                )
              + (long_term_physical_gib * price_long_term_physical)

forecast_total_cost_difference = logical_cost - physical_cost
```

*(Note: In `TABLE_STORAGE`, `active_physical_bytes` already includes baseline
active data and `time_travel_physical_bytes`. Adding `fail_safe_physical_bytes`
completes the active physical storage footprint).*

-   **Positive Delta (`> 0`):** Physical billing is forecasted to have lower
    total cost.
-   **Negative Delta (`< 0`):** Logical billing is cheaper; transitioning to
    Physical billing would increase costs.

### Step 3: Evaluate Decision Rules & Trade-offs

1.  **Break-Even Compression Threshold:**
    -   *Baseline Ratio:* Physical rates (\$0.04/GiB active, \$0.02/GiB
        long-term in US) are roughly **2x** Logical rates (\$0.02/GiB active,
        \$0.01/GiB long-term). In standard US regions, data must compress
        **better than 2:1 (>2x)** (`logical_volume / physical_volume > 2`)
        before accounting for overhead.
    -   *Regional & Contract Adjustments:* For non-US regions or enterprise
        contracts, calculate the specific `price_physical / price_logical` ratio
        dynamically using current rates from
        [BigQuery Storage Pricing](https://cloud.google.com/bigquery/pricing#storage-pricing).
2.  **Time Travel & Fail-Safe Overhead:**
    -   Under **Logical** billing, Time Travel and Fail-Safe bytes are **free**.
    -   Under **Physical** billing, Time Travel and Fail-Safe bytes are **billed
        at the physical active rate**.
    -   High-churn workloads (frequent `UPDATE`/`DELETE` or daily full-table
        overwrites) inflate physical storage and require higher break-even
        compression (often 2.5x–3x+).

## 2. Actionable Recommendations

Determine the dataset's current storage billing model (via metadata or
`INFORMATION_SCHEMA.TABLE_STORAGE`):

### If Currently on Logical Billing:

-   **Physical is More Cost-Effective (`forecast_total_cost_difference > 0` &
    Low Churn):** Recommend updating the dataset storage billing model to
    `PHYSICAL` in dataset settings.
-   **High Churn but Strong Compression:** Recommend reducing the dataset Time
    Travel window (e.g., from 7 days down to 2 days) *before* transitioning to
    Physical billing to minimize overhead.
-   **Logical is More Cost-Effective (`forecast_total_cost_difference < 0`):**
    Recommend remaining on `LOGICAL` billing.

### If Currently on Physical Billing:

-   **Logical is More Cost-Effective (`forecast_total_cost_difference < 0`):**
    Recommend transitioning the dataset back to `LOGICAL` billing in dataset
    settings (verifying the 14-day lock-in cooldown has elapsed).
-   **Physical is Favorable but Inflated by Time Travel:** Recommend reducing
    the dataset Time Travel window to lower billable physical active bytes
    without changing the billing model.
-   **Physical is Optimal:** Recommend maintaining `PHYSICAL` billing.

## 3. Critical Footguns

-   **14-Day Cooldown (Hard Lock-in):** Once a dataset's storage billing model
    is updated, it **cannot be changed again for 14 days**. Verify compression
    and historical churn across a full cycle before advising a change.
-   **24-Hour Propagation Delay:** After updating the storage billing model on a
    dataset, it takes up to **24 hours** for the change to take effect and be
    reflected in storage billing calculations.
-   **Time Travel & Fail-Safe Incur Active Physical Rates:** Under Physical
    billing, both Time Travel (1–7 days) and Fail-Safe (7-day non-configurable
    disaster recovery) storage are billed at the **active physical rate**. In
    contrast, Time Travel and Fail-Safe bytes are completely free under Logical
    billing. For high-churn datasets, Time Travel + Fail-Safe overhead can
    outweigh compression savings.
-   **Free Tier Proration & Scope:** The 10 GiB monthly free tier is pooled
    across the Cloud Billing account and prorated per second (e.g., 100 GiB
    stored for 1 day is ~3.3 GiB-months, fitting within the free tier).
-   **Deletion Footgun on Physical Storage:** Deleting a table stops billing
    immediately under Logical storage, but continues accruing active physical
    charges for 9–14 days (Time Travel + 7-day Fail-Safe) under Physical
    storage.
storage_lifecycle_management.md 2.2 KB
# Storage Lifecycle Management (Retention & TTL Optimization)

Decision matrix and parameters for at-rest storage right-sizing.

## 1. Optimization Decision Matrix

<!-- mdformat off -->
| Target Area | Trigger / Condition | Action / Parameter | Expected Impact |
| :--- | :--- | :--- | :--- |
| **Partition TTL** | Staging dataset or rolling logs | Set `default_partition_expiration_days` or `partition_expiration_days` | Automatically drops expired partitions after window |
| **Time Travel Tuning** | Ephemeral tables on `PHYSICAL` storage | Set `max_time_travel_hours = 48` (2-day min) | Drops `time_travel_physical_bytes` by ~5/7 (~71%) |
| **Unpartitioned Table** | Mature table (>90d) with active-only spend | Partition table by date or timestamp | Unlocks 50% Long-Term discount on historical rows |
| **Dev/Test Replication** | Full CTAS staging table copies | Replace with `CREATE TABLE CLONE` | Billed only for delta blocks added/modified |
| **Disaster Recovery** | Point-in-time table backups | Replace with `CREATE SNAPSHOT TABLE` | Billed only for modified/deleted base rows |
| **Cold Compliance** | Data accessed <1 time/year | Export to GCS Archive + query via BigLake | ~8x cheaper than BigQuery long-term logical rate |
<!-- mdformat on -->

## 2. Savings Formulas & Calculation

```text
# Time Travel Reduction Savings (Physical billing only):
estimated_tt_savings = (
                         current_time_travel_gib
                         * (1 - (new_window_hours / current_window_hours))
                       ) * price_active_physical
```

## 3. Gotchas & Constraints

-   **DML Clock Reset:** Unpartitioned `UPDATE`/`MERGE` touches all partitions,
    resetting their 90-day long-term timer back to 0. Always filter `WHERE
    _PARTITIONDATE >= ...`.
-   **Fail-Safe Invariant:** Fail-Safe window is fixed at 7 days
    non-configurable; continues to accrue active physical storage charges after
    Time Travel ends.
-   **Logical Billing Applicability:** Time Travel and Fail-Safe bytes are free
    under `LOGICAL` billing; tuning `max_time_travel_hours` yields \$0 storage
    savings on Logical datasets.
-   **TTL Permanent Drop:** Data dropped via partition expiration cannot be
    recovered once Time Travel + Fail-Safe windows elapse.
table_partitioning_clustering.md 15.3 KB
# Table Partitioning & Clustering Strategy

Architectural guidelines, decision matrices, and DDL patterns for table design,
query pruning optimization, and storage efficiency.

## Table of Contents

-   [1. Decision Matrix: Partitioning vs. Clustering vs. Hybrid](#1-decision-matrix-partitioning-vs-clustering-vs-hybrid) (Lines 22-32)
-   [2. Partitioning Design Principles](#2-partitioning-design-principles) (Lines 34-66)
    -   [Partitioning Types by Column Type](#partitioning-types-by-column-type) (Lines 36-46)
    -   [Core Partitioning Invariants & Rules](#core-partitioning-invariants-rules) (Lines 48-66)
-   [3. Clustering Design Principles](#3-clustering-design-principles) (Lines 68-88)
    -   [Clustering Rules & Mechanics](#clustering-rules-mechanics) (Lines 70-88)
-   [4. Production DDL Templates](#4-production-ddl-templates) (Lines 90-178)
    -   [Recommended Hybrid Pattern (Partition + Cluster)](#recommended-hybrid-pattern-partition-cluster) (Lines 92-112)
    -   [Migrating an Existing Unpartitioned Table to Partitioned](#migrating-an-existing-unpartitioned-table-to-partitioned) (Lines 114-135)
    -   [Modifying the Clustering Specification](#modifying-the-clustering-specification) (Lines 137-178)
-   [5. Table Design & Recommendation Workflow (Given a Table or Schema)](#5-table-design-recommendation-workflow-given-a-table-or-schema) (Lines 180-235)
-   [6. Table Design Anti-Patterns & Architecture Constraints](#6-table-design-anti-patterns-architecture-constraints) (Lines 237-263)
-   [7. Telemetry & Data Retrieval Reference](#7-telemetry-data-retrieval-reference) (Lines 265-287)

## 1. Decision Matrix: Partitioning vs. Clustering vs. Hybrid

<!-- mdformat off -->
| Dimension | Partitioning (`PARTITION BY`) | Clustering (`CLUSTER BY`) | Hybrid (`PARTITION BY` + `CLUSTER BY`) |
| :--- | :--- | :--- | :--- |
| **Best For** | Low-cardinality values, temporal/date boundaries, date-based TTL retention. | High-cardinality values, multiple filter/group-by columns, frequent DML modifications. | Large temporal tables with multi-dimensional filtering (e.g., date + tenant/status). |
| **Pruning Mechanism** | **Partition Pruning:** Whole partitions are eliminated from scanning before execution. | **Block Pruning:** Capacitor data blocks within files are skipped dynamically during execution. | Two-tier pruning: Partition pruning narrows the time window, then block pruning skips blocks within partitions. |
| **Cost Estimation** | Known deterministically before query execution via dry-run (`totalBytesProcessed`). | Estimated dynamically during execution as blocks are evaluated. | Upfront partition scan bounds with execution-time block savings. |
| **Storage Lifecycle** | Unlocks **partition-level TTL** and 90-day long-term 50% storage price discount. | No partition-level expiration (data is co-located across storage blocks). | Enables partition TTL retention while optimizing intra-partition query performance. |
| **Limits** | Up to **10,000 partitions per table**. | Up to **4 clustering columns** per table. | 10,000 partition limit applies; clustering operates within each partition. |
<!-- mdformat on -->

## 2. Partitioning Design Principles

### Partitioning Types by Column Type

*   **`TIMESTAMP` Column:** `PARTITION BY TIMESTAMP_TRUNC(column_name, DAY)`
*   **`DATE` Column:** `PARTITION BY date_column` (or for monthly granularity:
    `PARTITION BY DATE_TRUNC(date_column, MONTH)`)
*   **`DATETIME` Column:** `PARTITION BY DATETIME_TRUNC(datetime_column, DAY)`
*   **Ingestion-Time Partitioning:** BigQuery assigns rows to partitions based
    on the ingestion time using the pseudo-column `_PARTITIONDATE` /
    `_PARTITIONTIME`.
*   **Integer-Range Partitioning:** Partition by an `INT64` column using
    `RANGE_BUCKET(column, GENERATE_ARRAY(start, end, interval))`.

### Core Partitioning Invariants & Rules

*   **10,000 Partition Quota Limit:** Each partitioned table can have up to
    10,000 partitions. If a table reaches or approaches this limit:
    *   *Solution:* Widen the partition time unit (e.g., switch from `HOUR` to
        `DAY`, or `DAY` to `MONTH`) and **cluster on the granular time column**
        (e.g. partition by month, cluster by timestamp). BigQuery automatically
        clusters data blocks within each partition.
*   **Enforce Partition Pruning (`require_partition_filter = true`):** For large
    tables, always set `require_partition_filter = true` to force queries to
    supply a partition predicate in the `WHERE` clause, preventing accidental
    multi-terabyte unpruned full-table scans.
*   **Avoid Over-Partitioning:** Do not create hourly partitions for low-volume
    tables. Partitioning that results in a small amount of data per partition
    (approximately less than 10 GB) increases the table's metadata, and can
    affect metadata access times when querying the table.
*   **Long-Term Storage Discount:** Partitions that are not modified for 90
    consecutive days automatically qualify for **50% cheaper long-term storage**
    pricing.

## 3. Clustering Design Principles

### Clustering Rules & Mechanics

*   **Up to 4 High-Cardinality Filtering & Grouping Columns:** Specify up to 4
    high-cardinality filtering and grouping columns (`WHERE` filters and `GROUP
    BY` keys) in the `CLUSTER BY` clause.
*   **Column Ordering is Critical:** BigQuery clusters data hierarchically based
    on the order of columns specified:
    *   Place the **most frequently filtered column** or the column with
        **equality filters** first (`col1`).
    *   Place secondary filter columns, range filter columns, or `GROUP
        BY`/`JOIN` keys next (`col2`, `col3`, `col4`).
    *   *Trap:* Filtering on `col2` without a predicate on `col1` significantly
        diminishes block pruning effectiveness.
*   **Supported Data Types:** `STRING` (first 1,024 characters), `INT64`,
    `NUMERIC`, `BIGNUMERIC`, `BOOL`, `TIMESTAMP`, `DATE`, `DATETIME`,
    `GEOGRAPHY`, `RANGE`.
*   **Automatic Re-Clustering:** BigQuery performs continuous, fully-managed
    background reclustering to maintain block sortedness as new data is appended
    or modified, at **zero slot cost**.

## 4. Production DDL Templates

### Recommended Hybrid Pattern (Partition + Cluster)

```sql
CREATE OR REPLACE TABLE `{project_id}.{dataset_id}.events`
(
  event_id STRING,
  customer_id STRING,
  event_type STRING,
  event_timestamp TIMESTAMP,
  payload JSON
)
-- Partition by DATE, TIMESTAMP, DATETIME, or INT64 range column:
PARTITION BY TIMESTAMP_TRUNC(event_timestamp, DAY)
-- Cluster on up to 4 high-cardinality filtering and grouping columns:
CLUSTER BY customer_id, event_type
OPTIONS (
  require_partition_filter = true,
  partition_expiration_days = 365,
  description = 'High-volume events partitioned by day and clustered by customer'
);
```

### Migrating an Existing Unpartitioned Table to Partitioned

You cannot directly convert an existing non-partitioned table to a partitioned
table via `ALTER TABLE`, and it is not possible to use the `OR REPLACE` modifier
to replace a table with a different kind of partitioning. Instead, use a `CREATE
TABLE ... PARTITION BY ... CLUSTER BY ... AS SELECT * FROM ...` (CTAS) statement
to create a new partitioned table by querying the data in the existing table (or
`DROP` the table first and then recreate it)—partitioning by a `DATE`,
`TIMESTAMP`, `DATETIME`, or `INT64` (`RANGE_BUCKET`) column, clustering on up to
4 high-cardinality filtering and grouping columns (`WHERE` and `GROUP BY`), and
setting `require_partition_filter = true`:

```sql
CREATE TABLE `{project_id}.{dataset_id}.events_partitioned`
  -- Partition by DATE, TIMESTAMP, DATETIME, or INT64 range column:
  PARTITION BY TIMESTAMP_TRUNC(event_timestamp, DAY)
  -- Cluster on up to 4 high-cardinality filtering and grouping columns:
  CLUSTER BY customer_id, event_type
  OPTIONS (require_partition_filter = TRUE)
AS
SELECT * FROM `{project_id}.{dataset_id}.events_unpartitioned`;
```

### Modifying the Clustering Specification

Apply a new clustering specification to unpartitioned or partitioned tables in
two steps. First, update the clustering specification of the table to match the
new clustering:

```bash
bq update --clustering_fields=customer_id,status \
  {project_id}:{dataset_id}.{table_id}
```

The `--clustering_fields` value is a comma-separated list of column names to use
for clustering.

Then, to cluster all rows according to the new clustering specification, run the
following `UPDATE` statement. Propose this statement to the user rather than
running it directly:

```sql
UPDATE `{project_id}.{dataset_id}.{table_id}`
SET customer_id = customer_id
WHERE true;
```

The `UPDATE` must supply a partition filter if the table has
`require_partition_filter = true`, and a single job cannot modify more than
4,000 partitions (the per-job modification limit). For partitioned tables,
re-cluster in bounded batches:

```sql
UPDATE `{project_id}.{dataset_id}.{table_id}`
SET customer_id = customer_id
WHERE {partition_column} >= '{range_start}'
  AND {partition_column} < '{range_end}';
```

Repeat over consecutive ranges of fewer than 4,000 partitions until the whole
table is covered.

Tell the user that applying a new clustering specification to a table in
long-term storage reverts that table to
[active storage pricing](https://cloud.google.com/bigquery/pricing#storage-pricing).

## 5. Table Design & Recommendation Workflow (Given a Table or Schema)

When asked to recommend a partitioning and clustering strategy for a specific
table or schema:

1.  **Step 1: Identify Partitioning Key & Time Granularity**

    *   *Audit Existing Table Configuration:* Before proposing changes, check
        `INFORMATION_SCHEMA.COLUMNS` (`is_partitioning_column = 'YES'`,
        `data_type`, `clustering_ordinal_position`) and
        `INFORMATION_SCHEMA.TABLE_OPTIONS` (`option_name =
        'require_partition_filter'`) for the target dataset, or run `bq show
        --format=prettyjson {project_id}:{dataset_id}.{table_id}`
        (`timePartitioning`, `rangePartitioning`, `clustering`,
        `requirePartitionFilter`) to confirm whether the table already has
        `DATE`, `TIMESTAMP`, `DATETIME`, or `INT64` integer-range partitioning,
        clustering columns, and partition filter enforcement.
    *   *Scan Column Types:* Look for `TIMESTAMP`, `DATE`, or `DATETIME` columns
        representing primary event generation time.
    *   *Check the 10,000 Partition Quota Limit:*
        *   **`DAY` Partitioning (Default):** Optimal for 1–7 year lifespans
            (~365 to ~2,555 partitions).
        *   **`HOUR` Partitioning:** Choose it only for tables with a high
            volume of data spanning a short date range — typically less than six
            months of timestamp values. Make sure the resulting partition count
            stays within the 10,000 partition limit.
        *   **`MONTH` or `YEAR` Partitioning:** For historical archives (>10
            years), partition by `MONTH` and cluster by the timestamp.
    *   *No Temporal Column:* Evaluate integer range partitioning
        (`RANGE_BUCKET`) for incremental IDs, or ingestion-time partitioning
        (`_PARTITIONTIME`) for append-only log streams.

2.  **Step 2: Select & Order Clustering Columns (Up to 4 Columns)**

    *   *Candidate Columns:* High-cardinality dimension columns frequently
        present in `WHERE` equality filters, `JOIN ON` clauses, or `GROUP BY`
        aggregations (e.g., `customer_id`, `organization_id`, `status`).
    *   *Column Ordering Rules:*
        *   `col1`: The most frequently filtered column or equality/tenant
            identifier (`customer_id`).
        *   `col2`, `col3`: Secondary dimensions or range filter attributes
            (`event_type`, `created_at`).
        *   *Order Trap:* Queries filtering on `col2` without a predicate on
            `col1` cannot perform efficient block pruning.

3.  **Step 3: Output Production DDL & Guardrails**

    *   Generate complete `CREATE TABLE` DDL, including CTAS migrations. To
        modify a table's clustering specification, use the two-step sequence in
        Section 4.
    *   Add `require_partition_filter = true` (`ALTER TABLE
        {dataset_id}.{table_id} SET OPTIONS (require_partition_filter = true)`)
        for high-volume production tables to prevent accidental unpruned
        full-table scans.
    *   Add `partition_expiration_days = N` for staging, ETL, or rolling log
        tables to automate data cleanup.

## 6. Table Design Anti-Patterns & Architecture Constraints

-   **`ALTER TABLE` Partitioning Invariant:** BigQuery **does not support
    altering an existing unpartitioned table to become partitioned**. You must
    create a new partitioned table using CTAS or a load job. `ALTER TABLE` does
    not support setting or changing a table's clustering; use `bq update
    --clustering_fields` (Section 4).
-   **Small-Partition Anti-Pattern (<10 GB per Partition):** Prefer clustering
    over partitioning when partitioning would yield **less than ~10 GB per
    partition**. Creating many small partitions inflates table metadata and
    slows metadata access at query time without yielding scan savings.
    *(Separately, on-demand query compute charges enforce a 10 MiB data
    processed minimum per referenced table and per query, regardless of table or
    partition size).*
-   **1,024-Character String Limit:** For `STRING` clustering columns, BigQuery
    evaluates only the **first 1,024 characters** for block pruning. Do not
    cluster on long free-text descriptions or raw JSON payloads; extract concise
    identifiers.
-   **Streaming Buffer Compaction (`__UNPARTITIONED__`):** Rows recently
    streamed via the BigQuery Storage Write API initially reside in the
    `__UNPARTITIONED__` partition with a `NULL` `_PARTITIONTIME`. These rows
    cannot be pruned by partition filters until extracted into permanent
    partitions by BigQuery's background compaction.
-   **Query Filter Optimization:** To leverage partition and clustering pruning
    effectively in query execution, predicates must use compile-time constants.
    For query-level `WHERE`-clause rewrites and function anti-patterns, refer to
    the `bigquery-optimization` skill.

## 7. Telemetry & Data Retrieval Reference

If the `bigquery-observability` skill is available in your workspace, refer to
its shared telemetry references for canonical query templates and schema
dictionaries. All essential table design workflows, DDL templates, and
remediation levers are self-contained within this guide.

*   **Table Partitioning, Clustering & Filter Enforcement Audit:** See the
    `bigquery-observability` skill (`references/storage_footprints.md`, section
    "Table Partitioning, Clustering & Filter Enforcement Audit") to query
    `INFORMATION_SCHEMA.COLUMNS` and `INFORMATION_SCHEMA.TABLE_OPTIONS` for
    unpartitioned tables, partitioning column types, clustering columns, and
    `require_partition_filter`.
*   **High-Scan Referenced Tables Discovery:** See the `bigquery-observability`
    skill (`references/compute_ondemand_billable.md`, section "CORE RULE: The
    Golden Base CTE (bytes_billed_cte)") to group
    `INFORMATION_SCHEMA.JOBS_BY_PROJECT` by
    `query_info.query_hashes.normalized_literals` for exact job-level
    `total_bytes_billed` and `total_bytes_processed` attribution, and unnest
    `referenced_tables` to discover candidate tables (do not sum job-level bytes
    across multi-table joins; cross-check candidate table size via
    `total_logical_bytes` in `INFORMATION_SCHEMA.TABLE_STORAGE` before
    recommending partitioning).

License (Apache-2.0)

View full license text
Licensed under the Apache License, Version 2.0. See https://github.com/google/skills/blob/main/LICENSE