Installation

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

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

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

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

Download and extract to your repository:

.github/skills/bigquery-observability/

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

Skill Files (11)

SKILL.md 16.9 KB
---
name: bigquery-observability
metadata:
  version: "1.2.3"
  category: BigDataAndAnalytics
  publisher: google
description: >-
  Provides data-retrieval best practices, tool selection guidance, and
  performant SQL query syntax for BigQuery telemetry across INFORMATION_SCHEMA,
  Cloud Monitoring, and the REST API. Use when the telemetry to fetch is already
  known, selecting telemetry tools, writing performant INFORMATION_SCHEMA
  queries, retrieving telemetry for diagnosing single-job performance
  bottlenecks, investigating slot contention, job concurrency and queue latency,
  analyzing reservation capacity, utilization and autoscaling saturation, or
  auditing capacity-based and on-demand compute and storage resource billable
  usage. Don't use for root-cause diagnosis or symptom troubleshooting when the
  cause is unknown (use bigquery-troubleshooting first), or for writing or
  optimizing business logic SQL (use bigquery-optimization).
---

# BigQuery Observability

## 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-observability)"`
and append `agent-skills/1.0 (skill:bigquery-observability)` to `User-Agent` headers.

## Tool Selection

<!-- mdformat off -->

| Tool | Primary Use Cases | Strengths & Capabilities | When to Avoid / Limitations |
| --- | --- | --- | --- |
| **`INFORMATION_SCHEMA` (`I_S`)** | Historical analysis, cohort comparison (`normalized_literals`), discovery of fast/slow windows, reservation/project timelines, multi-job aggregates, cost/billing tracing. | Flexible SQL querying across `JOBS`, `JOBS_TIMELINE`, and `RESERVATIONS`; supports custom time windows and grouping. | Avoid for high-frequency real-time polling or single-job point-lookups (can consume slots and take seconds to execute). |
| **REST API (`jobs.api` / `reservation.api`)** | Single-job point-lookup, real-time stage bottleneck diagnosis, automated pipeline status checks, reservation/capacity commitment configuration inspection (`reservations.get`, `reservations.list`). | Zero-SQL overhead, fast REST/CLI point-lookups (`bq show -j`, `bq show --reservation`), instant access to `performanceInsights`, `queryPlan`, and structural metadata. | Avoid for aggregate analysis across thousands of jobs, cross-project historical comparison, or system timeline aggregations. |
| **`Cloud Monitoring` (Metrics Explorer / Charts)** | Real-time alerting, fleet-wide dashboards, continuous slot utilization tracking, high-level SLA/SLO monitoring. | Out-of-the-box charts for slot utilization, query throughput, `PENDING` queue depth, and execution latency; low-latency alerting without running queries. | Avoid for SQL-level debugging, individual query text inspection, or stage-level execution detail. |

<!-- mdformat on -->

## Prerequisites & Environment Setup

Before retrieving telemetry or running observability queries, ensure the
Google Cloud environment and project are configured:

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 the BigQuery and Cloud Monitoring APIs are
    enabled:

    ```bash
    gcloud services enable bigquery.googleapis.com monitoring.googleapis.com
    ```

4.  **Authentication**: Authenticate the environment:
    *   CLI queries and `bq` commands: `gcloud auth login`
    *   SDKs and automated client tools:
        `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.jobUser`: Submitting queries, own-job CLI
            fallback (`bq ls -j`, `bq show -j`), and reading
            `PROJECT_OPTIONS` (pair with read roles below to query
            `INFORMATION_SCHEMA`).
        *   `roles/bigquery.user`: Querying user-scoped telemetry
            (`JOBS_BY_USER`, `JOBS_TIMELINE_BY_USER`, `SESSIONS_BY_USER`)
            and submitting queries (supersedes `roles/bigquery.jobUser`).
        *   `roles/bigquery.metadataViewer`: Inspecting table, dataset,
            and storage metadata (`TABLES`, `COLUMNS`, `TABLE_STORAGE`,
            `TABLE_STORAGE_USAGE_TIMELINE`, `SCHEMATA`,
            `SCHEMATA_OPTIONS`).
        *   `roles/bigquery.resourceViewer` or `roles/bigquery.admin`:
            Querying project-, folder-, or organization-level jobs at
            the matching resource scope, and reservation, capacity
            commitment, and assignment telemetry on the reservations
            administration project.
        *   `roles/recommender.viewer` (optional): Querying
            `RECOMMENDATIONS` and `INSIGHTS` views (dataset IAM
            recommendations also require `iam.roles.get`/`list` and
            `bigquery.datasets.getIamPolicy`).
        *   `roles/monitoring.viewer`: Reading Cloud Monitoring metrics.

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
    ```

## Workflow

1.  **Single-Job Point-Lookup (Zero-SQL Overhead):** For single-job slowness or
    inspection, always prioritize the REST API or CLI (`bq show -j`) first. It
    provides zero-SQL overhead and fast point-lookups for internal stage
    bottlenecks (`performanceInsights`, `queryPlan`, shuffle spill).

    ```bash
    bq show --location={location} -j {project_id}:{job_id}
    ```

2.  **Diagnostic Transition Logic:** If no job-level issues are found (e.g. no
    clear internal bottlenecks), the investigation should transition to
    system-level `INFORMATION_SCHEMA` queries (such as `JOBS_TIMELINE` or
    `RESERVATIONS_TIMELINE`) to check for broader issues like slot contention,
    queueing delay, or noisy neighbors.

## Best Practices for Writing `INFORMATION_SCHEMA` Queries

Every query against a BigQuery `INFORMATION_SCHEMA` view must be qualified with
either a **region qualifier** or a **dataset qualifier**, optionally prefixed by
a **project qualifier**.

### Qualification Syntax & Scope Matching

1.  **Region-Qualified Syntax:**

    ```googlesql
    `{project_id}`.`region-{region}`.INFORMATION_SCHEMA.{view}
    ```

    *Example:* `` `my-project`.`region-us`.INFORMATION_SCHEMA.JOBS``

    *Applies to:* Regional telemetry views (`JOBS*`, `JOBS_TIMELINE*`,
    `RESERVATIONS*`, `CAPACITY_COMMITMENTS*`, `TABLE_STORAGE*`,
    `STREAMING_TIMELINE*`). The client query execution location MUST match the
    `region-{region}` qualifier (or BigQuery throws: `Not found: Table
    {project_id}:region-{region}.INFORMATION_SCHEMA.{view} was not found in
    location {location}`).

2.  **Dataset-Qualified Syntax:**

    ```googlesql
    `{project_id}`.`{dataset_id}`.INFORMATION_SCHEMA.{view}
    ```

    *Example:* `` `my-project`.`analytics`.INFORMATION_SCHEMA.TABLES``

    *Applies to:* Dataset-scoped views (`PARTITIONS`, `SEARCH_INDEXES`,
    `SEARCH_INDEX_COLUMNS`, `SEARCH_INDEX_OPTIONS`,
    `SEARCH_INDEX_COLUMN_OPTIONS`, `VECTOR_INDEXES`, `VECTOR_INDEX_COLUMNS`,
    `VECTOR_INDEX_OPTIONS`, `TABLE_CONSTRAINTS`, `KEY_COLUMN_USAGE`;
    `SEARCH_INDEXES_BY_ORGANIZATION` uses `region-`). Never use `region-` with
    `PARTITIONS`, dataset-level `SEARCH_INDEX*` views (which fail with
    `Not found`), or `VECTOR_INDEX*` views (which silently return 0 rows);
    prefer `{dataset_id}` for `TABLE_CONSTRAINTS` and `KEY_COLUMN_USAGE` per
    public documentation.

3.  **Dual-Scoped Views:** Views like `TABLES`, `TABLE_OPTIONS`,
    `TABLE_SNAPSHOTS`, `COLUMNS`, `COLUMN_FIELD_PATHS`, `VIEWS`,
    `MATERIALIZED_VIEWS`, `ROW_ACCESS_POLICIES`, `ROUTINES`, `ROUTINE_OPTIONS`,
    and `PARAMETERS` can be qualified with either `{dataset_id}` or
    `region-{region}` depending on whether dataset or region-wide analysis is
    required.

4.  **Project Qualifier (`{project_id}`):** Optional. If omitted, queries
    default to the project in which the query is executing. Specifying a project
    qualifier on organization-level views (e.g. `JOBS_BY_ORGANIZATION`) has no
    impact on results.

### Principle of Least Privilege & Scope Selection

When constructing `INFORMATION_SCHEMA` queries, **always select the scope and
view variant with the least IAM permission requirement** that satisfies the
analytical need:

1.  **User-Level over Project-Level (`_BY_USER`):** When diagnosing queries or
    sessions executed by the current user, use `_BY_USER` (e.g. `JOBS_BY_USER`,
    `SESSIONS_BY_USER`). This requires only `bigquery.jobs.list` (granted via
    `roles/bigquery.user`), avoiding the need for `bigquery.jobs.listAll` or
    `roles/bigquery.admin`. If `JOBS_BY_USER` also returns `403 Access Denied`
    (e.g. when the caller only holds `roles/bigquery.jobUser`, which grants
    `bigquery.jobs.create` but not `bigquery.jobs.list`), fall back to
    `bq ls -j -n {max_results} {project_id}` for a zero-compute CLI job listing.
2.  **Dataset-Level over Region/Project-Level:** When querying table metadata,
    columns, or views for a specific dataset, qualify with `{dataset_id}` rather
    than `region-{region}` when project-level metadata access is restricted.
    Dataset-scoped queries require permissions only on that target dataset.
3.  **Project-Level over Org/Folder-Level (`_BY_PROJECT`):** Always start with
    project-scoped views before escalating to `_BY_FOLDER` or
    `_BY_ORGANIZATION`. Folder and organization queries require broad folder/org
    IAM permissions (`bigquery.jobs.listAll` or `bigquery.tables.list` at the
    Org/Folder node).
    *   **Admin Project vs. Query Running Project:** When investigating inside a
        **Query Running Project**, `JOBS_BY_PROJECT` (and
        `JOBS_TIMELINE_BY_PROJECT`) captures that project's query stats.
        However, in BigQuery Editions, reservations and commitments
        (`RESERVATIONS*`, `CAPACITY_COMMITMENTS*`, `ASSIGNMENTS*`) live in an
        **Admin Project** whose `JOBS_BY_PROJECT` view typically has no query
        running stats. When starting from an admin project or aggregating
        workload across all projects sharing a reservation, query
        `JOBS_BY_ORGANIZATION` (or `JOBS_TIMELINE_BY_ORGANIZATION`) filtered by
        `reservation_id` (`{admin_project_id}:{location}.{reservation_name}`;
        note multi-region locations use uppercase `US` or `EU`, or compare with
        `LOWER(reservation_id)`).
4.  **Metadata Roles over Data Roles:** For table and storage introspection,
    prefer `roles/bigquery.metadataViewer` (which provides `bigquery.tables.get`
    and `bigquery.tables.list`) over `roles/bigquery.dataViewer` or
    `roles/bigquery.dataOwner` when data read access (`bigquery.tables.getData`)
    is not needed. (Note: `INFORMATION_SCHEMA.PARTITIONS` uniquely requires
    `bigquery.tables.getData`).

### Execution Guardrails & Query Invariants

*   **Mandatory Partition & Time Filtering:** Always filter on `creation_time`
    (e.g., `creation_time >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 3
    DAY)`) or `usage_date` to avoid full metadata table scans.
*   **Script Wrapper Exclusion:** Add `AND (statement_type != 'SCRIPT' OR
    statement_type IS NULL)` when aggregating compute spend to avoid
    double-counting parent scripts and child jobs.
*   **Column Pruning:** Never use `SELECT *` against `INFORMATION_SCHEMA`; only
    project required columns.
*   **Dry Run & Cost Estimation:** Use a dry run (`bq query --dry_run
    --use_legacy_sql=false "{query}"` or API `dryRun=true`) before executing
    complex queries, multi-view joins, or large scans to validate syntax and
    estimate `totalBytesProcessed` at zero cost.
*   **Empty Regional Scope (0 Rows):** If the execution location matches the
    qualifier, but the project has no datasets or jobs in that region, the query
    succeeds and returns **0 rows**. Never assume 0 rows means 0 usage—always
    verify the target dataset locations.
*   **Non-Hierarchical Region Scope:** Region qualifiers are not hierarchical.
    Multi-regions do not encompass single regions (e.g. `region-us` returns only
    multi-region `US` metadata and does not include single regions like
    `region-us-central1`).
*   **No Multi-Region Aggregation in SQL:** Region qualifiers cannot be joined
    cross-region in a single query (e.g. `region-us` cannot join `region-eu`).
*   **Uncached Execution & Minimum Scan Size:** `INFORMATION_SCHEMA` query
    results are never cached. On-demand queries incur a minimum of 10 MB of data
    processing charges per execution.

## Domain References & SQL Queries

### Telemetry Query Guides

*   **On-Demand Compute: Billed Bytes**
    (`references/compute_ondemand_billable.md`): Authoritative Golden CTE
    (`bytes_billed_cte`), timezone-aligned billing date extraction (PST8PDT),
    BQML CREATE_MODEL 50x multiplier rules, script wrapper deduplication, and
    row-level security (RLS) masking checks.
*   **Capacity Compute: Billable Slots & Commitments**
    (`references/compute_capacity_billable.md`): Query templates for auditing
    billable capacity hours across 1-Year/3-Year commitments, uncovered baseline
    PAYG slots, and dynamic autoscaling hours.
*   **Storage Footprints & Usage (Bytes Stored)**
    (`references/storage_footprints.md`): Storage snapshot queries, compression
    ratio calculations, Time Travel / Fail-Safe churn, daily average GiB
    time-integrals, billing model evaluation, and search index coverage.

### Performance & Troubleshooting Guides

*   **Job Performance Queries** (`references/job_performance_queries.md`):
    Queries for evaluating individual and aggregate job performance, stage
    bottleneck flags, comparable jobs via normalized literals
    (`query_info.query_hashes.normalized_literals`), BI Engine acceleration,
    metadata cache (cmeta) acceleration, search index usage, materialized view
    rewrite usage, and execution variance outliers.
*   **Resource Contention Queries**
    (`references/resource_contention_queries.md`): Queries for diagnosing slot
    contention, queue latency, per-minute concurrency/queue timelines, and
    1-second reservation slot saturation.
*   **Capacity & Configuration Queries**
    (`references/capacity_and_configuration_queries.md`): Queries for evaluating
    second-by-second baseline/max capacity ceilings, autoscaling saturation
    timelines, and auditing configuration changes
    (`RESERVATION_CHANGES_BY_PROJECT`, `ASSIGNMENT_CHANGES_BY_PROJECT`).

### Schema Dictionaries (Column Definitions & Units)

*   **Compute & Capacity Schema Dictionary** (`references/schema_compute.md`):
    Complete column dictionary, physical units, and least-privilege IAM roles
    for all compute, job, session, reservation, capacity commitment, assignment,
    and BI Engine views (`JOBS*`, `JOBS_TIMELINE*`, `SESSIONS_BY_USER`,
    `SESSIONS_BY_PROJECT`, `RESERVATIONS*`, `RESERVATION_CHANGES*`,
    `RESERVATIONS_TIMELINE*`, `CAPACITY_COMMITMENTS*`,
    `CAPACITY_COMMITMENT_CHANGES*`, `ASSIGNMENTS*`, `ASSIGNMENT_CHANGES*`,
    `BI_CAPACITIES`, `BI_CAPACITY_CHANGES`).
*   **Storage & Data Catalog Schema Dictionary**
    (`references/schema_storage.md`): Complete column dictionary, physical
    units, and least-privilege IAM roles for all table storage, partition,
    column, snapshot, dataset, constraint, and replication views
    (`TABLE_STORAGE*`, `TABLE_STORAGE_USAGE_TIMELINE*`, `TABLES`,
    `TABLE_OPTIONS`, `COLUMNS`, `COLUMN_FIELD_PATHS`, `PARTITIONS`, `VIEWS`,
    `MATERIALIZED_VIEWS`, `TABLE_SNAPSHOTS`, `TABLE_CONSTRAINTS`,
    `KEY_COLUMN_USAGE`, `SCHEMATA`, `SCHEMATA_OPTIONS`, `SCHEMATA_REPLICAS*`,
    `SCHEMATA_LINKS`, `SHARED_DATASET_USAGE`).
*   **Platform, Governance & Ingestion Schema Dictionary**
    (`references/schema_others.md`): Complete column dictionary, physical units,
    and least-privilege IAM roles for all remaining views including Access
    Control (`OBJECT_PRIVILEGES`, `ROW_ACCESS_POLICIES`), Streaming Ingestion
    (`STREAMING_TIMELINE*`, `WRITE_API_TIMELINE*`), Configuration Options
    (`PROJECT_OPTIONS`, `PROJECT_OPTIONS_CHANGES`, `EFFECTIVE_PROJECT_OPTIONS`,
    `ORGANIZATION_OPTIONS`, `ORGANIZATION_OPTIONS_CHANGES`), Insights &
    Recommendations (`RECOMMENDATIONS*`, `INSIGHTS*`), and Indexes/BI
    Engine/Routines (`SEARCH_INDEXES*`, `SEARCH_INDEX_COLUMNS`,
    `SEARCH_INDEX_OPTIONS`, `VECTOR_INDEXES`, `VECTOR_INDEX_COLUMNS`,
    `VECTOR_INDEX_OPTIONS`, `BI_CAPACITIES`, `BI_CAPACITY_CHANGES`, `ROUTINES`,
    `ROUTINE_OPTIONS`, `PARAMETERS`).
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-observability)" \
    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-observability)` 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-observability)
    ```

-   **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.
capacity_and_configuration_queries.md 6.6 KB
# Capacity & Configuration Queries

Telemetry and SQL queries for evaluating reservation slot capacity, monitoring
autoscaling behavior and headroom saturation, inspecting capacity commitments
and assignments, and auditing configuration changes.

## Table of Contents

-   [Reservation Slot Capacity & Autoscaling Saturation Timeline (1-Second Resolution)](#reservation-slot-capacity-autoscaling-saturation-timeline-1-second-resolution)
    (Lines 14-168)
-   [Auditing Reservation & Assignment Configuration Changes](#auditing-reservation-assignment-configuration-changes)
    (Lines 169-189)

## Reservation Slot Capacity & Autoscaling Saturation Timeline (1-Second Resolution)

Tracks second-by-second baseline capacity, active autoscaling slots, and maximum
capacity ceilings. Accurately calculates baseline and autoscale slots by
accounting for:

-   **Primary vs Failover Regions (`is_creation_region`)**: Distinguishes
    primary baseline from disaster-recovery secondary region baseline.
-   **Predictable Scaling Modes (`scaling_mode`)**: When `scaling_mode IN
    ('ALL_SLOTS', 'AUTOSCALE_ONLY')`, `max_slots` includes baseline slots, so
    autoscale max is `max_slots - slots_assigned`.
-   **Per-Second Telemetry (`per_second_details`)**: Unnests second-level
    records or expands minute intervals across 60 seconds.
-   **Autoscale Saturation**: Detects when autoscaling reached its maximum
    capacity headroom (`autoscale_current_slots >= total_autoscale_max`).

```sql
WITH
  reservation_timeline_raw AS (
    SELECT
      period_start,
      project_id AS admin_project_id,
      reservation_name,
      reservation_id,
      edition,
      scaling_mode,
      is_creation_region,
      ignore_idle_slots,
      slots_assigned,
      max_slots,
      autoscale,
      per_second_details
    FROM
      `{admin_project_id}`.`region-{region}`.INFORMATION_SCHEMA.RESERVATIONS_TIMELINE_BY_PROJECT
    WHERE
      period_start >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 7 DAY)
      AND reservation_name = '{reservation_name}'
  ),
  reservation_per_second AS (
    SELECT
      s.start_time AS second_timestamp,
      TIMESTAMP_TRUNC(period_start, MINUTE) AS window_minute,
      reservation_name,
      reservation_id,
      edition,
      scaling_mode,
      ignore_idle_slots,
      -- Primary region baseline & autoscale headroom
      IF(is_creation_region, IFNULL(s.slots_assigned, 0), 0) AS baseline_slots,
      IF(
        is_creation_region,
        IF(
          scaling_mode IN ('ALL_SLOTS', 'AUTOSCALE_ONLY'),
          IFNULL(max_slots, 0) - IFNULL(s.slots_assigned, 0),
          0),
        0) AS max_slots_exclude_baseline,
      -- Failover secondary region baseline & autoscale headroom
      IF(NOT is_creation_region, IFNULL(s.slots_assigned, 0), 0) AS failover_baseline_slots,
      IF(
        NOT is_creation_region,
        IF(
          scaling_mode IN ('ALL_SLOTS', 'AUTOSCALE_ONLY'),
          IFNULL(max_slots, 0) - IFNULL(s.slots_assigned, 0),
          0),
        0) AS failover_max_slots_exclude_baseline,
      IFNULL(s.autoscale_current_slots, 0) AS autoscale_current_slots,
      IFNULL(s.autoscale_max_slots, 0) AS autoscale_max_slots,
      IFNULL(s.borrowed_slots, 0) AS borrowed_slots
    FROM
      reservation_timeline_raw,
      UNNEST(
        IF(
          ARRAY_LENGTH(per_second_details) > 0,
          ARRAY(
            SELECT AS STRUCT
              s.start_time,
              s.autoscale_current_slots,
              s.autoscale_max_slots,
              s.slots_assigned,
              s.borrowed_slots
            FROM
              UNNEST(per_second_details) AS s
          ),
          ARRAY(
            SELECT AS STRUCT
              s AS start_time,
              autoscale.current_slots AS autoscale_current_slots,
              autoscale.max_slots AS autoscale_max_slots,
              slots_assigned AS slots_assigned,
              0 AS borrowed_slots
            FROM
              UNNEST(
                GENERATE_TIMESTAMP_ARRAY(
                  period_start,
                  TIMESTAMP_ADD(period_start, INTERVAL 59 SECOND),
                  INTERVAL 1 SECOND)) AS s
          ))) AS s
  ),
  capacity_metrics_per_second AS (
    SELECT
      second_timestamp,
      window_minute,
      reservation_name,
      edition,
      scaling_mode,
      -- Total baseline capacity across primary and failover regions
      (baseline_slots + failover_baseline_slots) AS total_baseline_capacity,
      -- Total maximum autoscale (excluding baseline)
      (autoscale_max_slots + max_slots_exclude_baseline + failover_max_slots_exclude_baseline)
        AS total_autoscale_max,
      -- Total ceiling capacity across baseline and autoscale
      (
        baseline_slots
        + failover_baseline_slots
        + autoscale_max_slots
        + max_slots_exclude_baseline
        + failover_max_slots_exclude_baseline) AS total_max_capacity,
      autoscale_current_slots,
      borrowed_slots AS idle_slots,
      -- Saturation Indicator: True when autoscale is maxed out
      IF(
        (autoscale_max_slots + max_slots_exclude_baseline + failover_max_slots_exclude_baseline) > 0
          AND autoscale_current_slots
            >= (
              autoscale_max_slots
              + max_slots_exclude_baseline
              + failover_max_slots_exclude_baseline),
        1,
        0) AS is_autoscale_saturated
    FROM
      reservation_per_second
  )
SELECT
  window_minute,
  reservation_name,
  edition,
  scaling_mode,
  ROUND(AVG(total_baseline_capacity), 1) AS avg_baseline_slots,
  ROUND(AVG(autoscale_current_slots), 1) AS avg_autoscale_slots,
  ROUND(AVG(total_autoscale_max), 1) AS avg_total_autoscale_max,
  ROUND(AVG(total_max_capacity), 1) AS avg_total_max_capacity,
  ROUND(AVG(idle_slots), 1) AS avg_borrowed_idle_slots,
  -- Percentage of seconds in the minute where autoscaling was saturated at max
  ROUND(AVG(is_autoscale_saturated) * 100, 1) AS pct_time_autoscale_saturated
FROM
  capacity_metrics_per_second
GROUP BY
  window_minute,
  reservation_name,
  edition,
  scaling_mode
ORDER BY
  window_minute DESC;
```

## Auditing Reservation & Assignment Configuration Changes

Audit historical modifications across reservation configurations, assignments,
and capacity commitments (e.g., `RESERVATION_CHANGES_BY_PROJECT`,
`ASSIGNMENT_CHANGES_BY_PROJECT`, `CAPACITY_COMMITMENT_CHANGES_BY_PROJECT`).

```sql
SELECT
  change_timestamp,
  action,
  reservation_name,
  slot_capacity AS new_slot_capacity,
  autoscale.max_slots AS new_autoscale_max_slots,
  user_email
FROM
  `{admin_project_id}`.`region-{region}`.INFORMATION_SCHEMA.RESERVATION_CHANGES_BY_PROJECT
WHERE
  change_timestamp >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 30 DAY)
ORDER BY
  change_timestamp DESC;
```
compute_capacity_billable.md 6.2 KB
# Billable Capacity Compute (Slots & Commitments)

## Table of Contents

-   [Edition Billable Slots Timeline](#edition-billable-slots-timeline) (Lines
    8-204)

## Edition Billable Slots Timeline

Commitments are purchased at the Edition level, but baseline and autoscaled
slots are assigned at the reservation level. To calculate billable slot hours
across 1-Year/3-Year commitments, uncovered baseline PAYG, and dynamic
autoscaling, join `CAPACITY_COMMITMENT_CHANGES_BY_PROJECT` and
`RESERVATIONS_TIMELINE`:

```googlesql
WITH
  commitments_with_next_plan AS (
    SELECT
      *,
      IFNULL(
        LEAD(commitment_plan)
          OVER (
            PARTITION BY capacity_commitment_id
            ORDER BY change_timestamp ASC
          ),
        commitment_plan) AS next_plan,
      IFNULL(
        LEAD(change_timestamp)
          OVER (
            PARTITION BY capacity_commitment_id
            ORDER BY change_timestamp ASC
          ),
        change_timestamp) AS next_plan_change_timestamp
    FROM
      `{admin_project_id}`.`region-{region}`.INFORMATION_SCHEMA.CAPACITY_COMMITMENT_CHANGES_BY_PROJECT
  ),
  capacity_changes_with_migration_delete AS (
    SELECT
      next_plan_change_timestamp AS change_timestamp,
      project_id,
      project_number,
      capacity_commitment_id,
      commitment_plan,
      state,
      slot_count,
      'DELETE' AS action,
      commitment_start_time,
      commitment_end_time,
      failure_status,
      renewal_plan,
      user_email,
      edition,
      is_flat_rate
    FROM
      commitments_with_next_plan
    WHERE
      commitment_plan <> next_plan
    UNION ALL
    SELECT
      *
    FROM
      `{admin_project_id}`.`region-{region}`.INFORMATION_SCHEMA.CAPACITY_COMMITMENT_CHANGES_BY_PROJECT
  ),
  capacity_commitment_slot_data AS (
    SELECT
      change_timestamp,
      capacity_commitment_id,
      commitment_plan,
      CASE
        WHEN action = "CREATE" OR action = "UPDATE"
          THEN
            IFNULL(
              IF(
                LAG(action)
                  OVER (
                    PARTITION BY capacity_commitment_id
                    ORDER BY change_timestamp ASC, action ASC
                  )
                  IN UNNEST(['CREATE', 'UPDATE']),
                slot_count - LAG(slot_count)
                  OVER (
                    PARTITION BY capacity_commitment_id
                    ORDER BY change_timestamp ASC, action ASC
                  ),
                slot_count),
              slot_count)
        ELSE
          IF(
            LAG(action)
              OVER (
                PARTITION BY capacity_commitment_id
                ORDER BY change_timestamp ASC, action ASC
              )
              IN UNNEST(['CREATE', 'UPDATE']),
            -1 * slot_count,
            0)
        END AS slot_count_delta
    FROM
      capacity_changes_with_migration_delete
    WHERE
      state = "ACTIVE"
      AND edition = '{edition}'
      AND change_timestamp <= TIMESTAMP('{end_timestamp}')
  ),
  running_total_commitments AS (
    SELECT
      change_timestamp,
      SUM(IF(commitment_plan = 'ANNUAL', slot_count_delta, 0))
        OVER (
          ORDER BY change_timestamp
          RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
        ) AS capacity_slot_annual,
      SUM(IF(commitment_plan = 'THREE_YEAR', slot_count_delta, 0))
        OVER (
          ORDER BY change_timestamp
          RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
        ) AS capacity_slot_three_year,
      SUM(slot_count_delta)
        OVER (
          ORDER BY change_timestamp
          RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
        ) AS capacity_slot_total
    FROM
      capacity_commitment_slot_data
  ),
  distinct_commitments AS (
    SELECT
      change_timestamp,
      MAX(capacity_slot_annual) AS capacity_slot_annual,
      MAX(capacity_slot_three_year) AS capacity_slot_three_year,
      MAX(capacity_slot_total) AS capacity_slot_total
    FROM
      running_total_commitments
    GROUP BY
      change_timestamp
  ),
  distinct_commitments_with_next AS (
    SELECT
      change_timestamp,
      IFNULL(
        LEAD(change_timestamp) OVER (ORDER BY change_timestamp ASC),
        CURRENT_TIMESTAMP()) AS next_change_timestamp,
      capacity_slot_annual,
      capacity_slot_three_year,
      capacity_slot_total
    FROM
      distinct_commitments
  ),
  reservation_period_slices AS (
    SELECT
      period_start,
      SUM(IF(is_creation_region, slot_capacity, 0)) AS total_baseline_slots,
      SUM(period_autoscale_slot_seconds) AS total_autoscale_slot_seconds
    FROM
      `{admin_project_id}`.`region-{region}`.INFORMATION_SCHEMA.RESERVATIONS_TIMELINE
    WHERE
      period_start >= TIMESTAMP('{start_timestamp}')
      AND period_start < TIMESTAMP('{end_timestamp}')
      AND edition = '{edition}'
    GROUP BY
      period_start
  ),
  edition_billable_slots_cte AS (
    SELECT
      r.period_start,
      IFNULL(c.capacity_slot_annual, 0) AS committed_slots_annual,
      IFNULL(c.capacity_slot_three_year, 0) AS committed_slots_three_year,
      r.total_baseline_slots,
      IF(
        r.total_baseline_slots - IFNULL(c.capacity_slot_total, 0) > 0,
        r.total_baseline_slots - IFNULL(c.capacity_slot_total, 0),
        0) AS uncovered_baseline_slots,
      r.total_autoscale_slot_seconds
    FROM
      reservation_period_slices r
    LEFT JOIN
      distinct_commitments_with_next c
      ON
        r.period_start >= c.change_timestamp
        AND r.period_start < c.next_change_timestamp
  )

-- Replace this SELECT with your specific troubleshooting aggregation, for example:
SELECT
  '{region}' AS region,
  '{edition}' AS edition,
  SUM(committed_slots_annual * 60) / 3600.0
    AS billable_committed_annual_slot_hours,
  SUM(committed_slots_three_year * 60) / 3600.0
    AS billable_committed_three_year_slot_hours,
  SUM(uncovered_baseline_slots * 60) / 3600.0
    AS billable_uncovered_baseline_slot_hours,
  SUM(total_autoscale_slot_seconds) / 3600.0
    AS billable_autoscaled_payg_slot_hours,
  SUM(
    (committed_slots_annual * 60)
    + (committed_slots_three_year * 60)
    + (uncovered_baseline_slots * 60)
    + total_autoscale_slot_seconds)
    / 3600.0 AS total_billable_slot_hours
FROM
  edition_billable_slots_cte;
```
compute_ondemand_billable.md 5.7 KB
# Billable On-Demand Compute (Bytes Billed)

## Table of Contents

-   [CORE RULE: The Golden Base CTE (bytes_billed_cte)](#core-rule-the-golden-base-cte-bytes_billed_cte)
    (Lines 10-112)
-   [Modifying the Output (Agent Instructions)](#modifying-the-output-agent-instructions)
    (Lines 113-121)

## CORE RULE: The Golden Base CTE (bytes_billed_cte)

Whenever you are asked to analyze, sum, filter, or group on-demand compute
costs, you MUST NOT query `INFORMATION_SCHEMA.JOBS` directly. You must ALWAYS
use the following Common Table Expression (CTE) as your absolute foundation.
This handles the extreme complexities of BigQuery billing, including
parent/child script double-counting, BQML 50x multipliers, and PST timezone
partitioning.

```googlesql
CREATE TEMP FUNCTION isBillable(error_result ANY TYPE)
AS (
  error_result IS NULL OR error_result.reason = 'stopped'
);

-- BigQuery hides the number of bytes billed on queries against tables with row-level security.
CREATE TEMP FUNCTION isMaybeUsingRowLevelSecurity(
  job_type STRING, tib_billed FLOAT64, error_result ANY TYPE)
AS (
  job_type = 'QUERY'
  AND tib_billed IS NULL
  AND isBillable(error_result)
);

WITH
  bytes_billed_cte AS (
    SELECT
      project_id,
      job_id,
      user_email,
      -- A hash grouping similar queries that only differ by literal values
      query_info.query_hashes.normalized_literals AS query_hash,
      total_bytes_billed,
      total_bytes_processed,
      referenced_tables,
      error_result,
      job_type,
      -- Jobs are billed by end_time in PST8PDT timezone, regardless of where the job ran
      EXTRACT(DATE FROM end_time AT TIME ZONE 'PST8PDT') AS billing_date,
      TIMESTAMP_DIFF(end_time, start_time, MILLISECOND) AS duration_ms,

      -- Multiply CREATE_MODEL by 50x. NOTE: I_S.JOBS does not track the specific model type.
      -- BQML pricing varies, so this conservatively assumes all models are the highest-billed (50x) types.
      (total_bytes_billed / 1024 / 1024 / 1024 / 1024)
        * CASE statement_type
          WHEN 'CREATE_MODEL' THEN 50
          ELSE 1
          END AS total_tb_billed,

      -- Flags queries where billed bytes were hidden/NULL due to Row-Level Security
      isMaybeUsingRowLevelSecurity(
        job_type,
        total_bytes_billed / 1024 / 1024 / 1024 / 1024,
        error_result) AS is_maybe_using_rls
    FROM
      -- JOBS and JOBS_BY_PROJECT are synonyms for project-scoped job history
      `{project_id}`.`region-{region}`.INFORMATION_SCHEMA.JOBS_BY_PROJECT
    WHERE
      -- Partition pruning: Pad creation_time by -2/+1 days to cover the target PST end_time billing window
      DATE(creation_time)
        BETWEEN DATE_SUB('{start_date}', INTERVAL 2 DAY)
        AND DATE_ADD('{end_date}', INTERVAL 1 DAY)
      AND EXTRACT(DATE FROM end_time AT TIME ZONE 'PST8PDT')
        BETWEEN '{start_date}'
        AND '{end_date}'
      AND job_type = 'QUERY'
      AND reservation_id IS NULL
      -- Scripts do not incur cost; their child queries do. Exclude to avoid double counting.
      AND (statement_type <> 'SCRIPT' OR statement_type IS NULL)
      AND isBillable(error_result)
  )
-- Default executable query: Daily spend & RLS masked query audit
SELECT
  '{region}' AS region,
  billing_date,
  ROUND(SUM(total_tb_billed), 4) AS total_tb_billed,
  COUNTIF(is_maybe_using_rls) AS jobs_using_row_level_security
FROM
  bytes_billed_cte
GROUP BY
  region,
  billing_date
ORDER BY
  billing_date;

-- Alternative troubleshooting aggregations:
-- 1. Top users by spend:
-- SELECT user_email, SUM(total_tb_billed) AS total_tb_billed FROM bytes_billed_cte GROUP BY 1 ORDER BY 2 DESC;
--
-- 2. Top queries by spend & processed bytes (job-level attribution, no multi-table fan-out):
-- SELECT query_hash, COUNT(1) AS query_count, SUM(total_tb_billed) AS total_tb_billed, SUM(total_bytes_processed) AS total_bytes_processed, ANY_VALUE(referenced_tables) AS sample_referenced_tables FROM bytes_billed_cte GROUP BY 1 ORDER BY 3 DESC LIMIT 10;
--
-- 3. Candidate tables referenced by high-scan queries (IMPORTANT: NEVER use SUM(total_bytes_billed) or SUM(total_bytes_processed) with UNNEST(referenced_tables), because job-level bytes repeat for every joined table; use COUNT(DISTINCT job_id), MAX(total_bytes_processed), and join TABLE_STORAGE for actual table size):
-- SELECT ref.project_id AS table_project_id, ref.dataset_id, ref.table_id, COUNT(DISTINCT c.job_id) AS referencing_job_count, MAX(c.total_bytes_processed) AS max_job_bytes_processed, MAX(s.total_logical_bytes) AS table_logical_bytes FROM bytes_billed_cte AS c, UNNEST(c.referenced_tables) AS ref LEFT JOIN `{project_id}`.`region-{region}`.INFORMATION_SCHEMA.TABLE_STORAGE AS s ON ref.project_id = s.project_id AND ref.dataset_id = s.table_schema AND ref.table_id = s.table_name GROUP BY 1, 2, 3 ORDER BY table_logical_bytes DESC, max_job_bytes_processed DESC LIMIT 20;
```

> **⚠️ BQML Multiplier Caveat:** BigQuery ML pricing for on-demand queries
> depends on the specific type of model being created. Because
> `INFORMATION_SCHEMA.JOBS` does not track which type of model was created, the
> `total_tb_billed` calculation conservatively assumes all `CREATE_MODEL`
> statements were creating the higher-billed (50x multiplier) model types. Keep
> this in mind when diagnosing massive BQML spikes.

## Modifying the Output (Agent Instructions)

-   **Placeholders**: Replace `{project_id}` with the target Google Cloud
    project ID, `{region}` with the dataset or job execution region (e.g. `us`,
    `europe-west1`), `{start_date}` with the start date (`YYYY-MM-DD`), and
    `{end_date}` with the end date (`YYYY-MM-DD`).
-   **Custom Aggregations**: To answer specific user questions, take the Golden
    CTE above and append your specific aggregation logic to the bottom of the
    script.
job_performance_queries.md 11.2 KB
# Query Performance Queries

Telemetry and SQL queries for evaluating individual and aggregate job
performance, discovering comparable job executions, analyzing slot consumption,
identifying query/stage bottlenecks, inspecting table-level job activity, and
verifying BI Engine / metadata cache (cmeta) acceleration.

## Table of Contents

-   [Single Job Performance & Stage Bottleneck Flags](#single-job-performance-stage-bottleneck-flags)
    (Lines 27-76)
-   [REST API Single-Job Point-Lookup & Stage Bottlenecks](#rest-api-single-job-point-lookup-stage-bottlenecks)
    (Lines 77-98)
-   [Finding Comparable Jobs](#finding-comparable-jobs) (Lines 99-130)
-   [BI Engine Acceleration Usage](#bi-engine-acceleration-usage) (Lines
    131-153)
-   [Table Metadata Cache (cmeta) Usage](#table-metadata-cache-cmeta-usage)
    (Lines 154-180)
-   [Search Index Usage](#search-index-usage) (Lines 181-209)
-   [Materialized View Rewrite Usage](#materialized-view-rewrite-usage) (Lines
    210-245)
-   [Query Performance Variance & Outlier Discovery](#query-performance-variance-outlier-discovery)
    (Lines 246-280)
-   [Stage Row Expansion, Shuffle Spill & Join Insights](#stage-row-expansion-shuffle-spill-join-insights)
    (Lines 281-341)

## Single Job Performance & Stage Bottleneck Flags

Retrieve execution duration, queuing delay, compute usage, bytes processed,
historical average duration, and stage bottleneck flags for a specific job.

```sql
SELECT
  job_id,
  user_email,
  state,
  creation_time,
  start_time,
  end_time,
  TIMESTAMP_DIFF(end_time, start_time, MILLISECOND) AS duration_ms,
  TIMESTAMP_DIFF(start_time, creation_time, MILLISECOND) AS pending_ms,
  total_slot_ms,
  ROUND(
    SAFE_DIVIDE(
      total_slot_ms, TIMESTAMP_DIFF(end_time, start_time, MILLISECOND)),
    1) AS avg_slots_used,
  total_bytes_processed,
  total_bytes_billed,
  reservation_id,
  query_info.performance_insights.avg_previous_execution_ms
    AS avg_previous_execution_ms,
  query_info.performance_insights.avg_previous_slot_ms AS avg_previous_slot_ms,
  query_info.performance_insights.avg_previous_bytes_processed
    AS avg_previous_bytes_processed,
  query_info.performance_insights.num_previous_successful_jobs
    AS num_previous_successful_jobs,
  (
    SELECT LOGICAL_OR(slot_contention)
    FROM
      UNNEST(
        query_info.performance_insights.stage_performance_standalone_insights)
  ) AS has_slot_contention,
  (
    SELECT LOGICAL_OR(insufficient_shuffle_quota)
    FROM
      UNNEST(
        query_info.performance_insights.stage_performance_standalone_insights)
  ) AS has_insufficient_shuffle_quota,
  error_result.message AS error_message
FROM
  `{project_id}`.`region-{region}`.INFORMATION_SCHEMA.JOBS_BY_PROJECT
WHERE
  creation_time >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 30 DAY)
  AND job_id = '{job_id}';
```

## REST API Single-Job Point-Lookup & Stage Bottlenecks

Use the REST API for fast, zero-SQL point-lookups to extract stage-level
execution graphs, wait ratios, and performance insights.

```bash
bq show --location={location} -j {project_id}:{job_id}
```

Key fields in JSON response:

-   `statistics.query.performanceInsights`: Execution bottleneck diagnostics
    (e.g., `stagePerformanceStandaloneInsights[].slotContention`,
    `stagePerformanceStandaloneInsights[].insufficientShuffleQuota`,
    `stagePerformanceChangeInsights[].inputDataChange`,
    `avgPreviousExecutionMs`).
-   `statistics.query.queryPlan[]`: Stage-by-stage stats including `slotMs`,
    `shuffleOutputBytes`, `shuffleOutputBytesSpilled`, `recordsRead`,
    `recordsWritten`, `computeMsAvg`, `computeMsMax`, `waitMsAvg`, `waitMsMax`,
    `computeRatioAvg`, `computeRatioMax`, `waitRatioAvg`, `waitRatioMax`,
    `readRatioAvg`, `readRatioMax`, `writeRatioAvg`, `writeRatioMax`.

## Finding Comparable Jobs

Use `query_info.query_hashes.normalized_literals` to discover past runs of the
same query template and rank by duration to find fast baseline executions.

```sql
SELECT
  job_id,
  creation_time,
  TIMESTAMP_DIFF(end_time, start_time, MILLISECOND) AS duration_ms,
  total_slot_ms,
  ROUND(SAFE_DIVIDE(total_slot_ms, TIMESTAMP_DIFF(end_time, start_time, MILLISECOND)), 1)
    AS avg_slots_used,
  total_bytes_processed,
  total_bytes_billed,
  reservation_id,
  (
    SELECT LOGICAL_OR(slot_contention)
    FROM UNNEST(query_info.performance_insights.stage_performance_standalone_insights)
  ) AS has_slot_contention
FROM
  `{project_id}`.`region-{region}`.INFORMATION_SCHEMA.JOBS_BY_PROJECT
WHERE
  creation_time >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 14 DAY)
  AND (statement_type != 'SCRIPT' OR statement_type IS NULL)
  AND state = 'DONE'
  AND query_info.query_hashes.normalized_literals = '{target_normalized_hash}'
ORDER BY
  duration_ms ASC
LIMIT 20;
```

## BI Engine Acceleration Usage

Verify whether queries leveraged BI Engine memory acceleration and diagnose
acceleration rejection reasons.

```sql
SELECT
  job_id,
  creation_time,
  total_slot_ms,
  bi_engine_statistics.bi_engine_mode,
  bi_engine_statistics.acceleration_mode,
  bi_engine_statistics.bi_engine_reasons
FROM
  `{project_id}`.`region-{region}`.INFORMATION_SCHEMA.JOBS_BY_PROJECT
WHERE
  creation_time >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 3 DAY)
  AND bi_engine_statistics IS NOT NULL
ORDER BY
  creation_time DESC
LIMIT 50;
```

## Table Metadata Cache (cmeta) Usage

Inspect whether queries leveraged table metadata caching (`cmeta`), check
staleness, and diagnose why metadata caching was unused.

```sql
SELECT
  job_id,
  creation_time,
  total_slot_ms,
  t.table_reference.project_id AS table_project_id,
  t.table_reference.dataset_id AS table_dataset_id,
  t.table_reference.table_id,
  t.unused_reason,
  t.explanation,
  t.staleness_seconds,
FROM
  `{project_id}`.`region-{region}`.INFORMATION_SCHEMA.JOBS_BY_PROJECT,
  UNNEST(metadata_cache_statistics.table_metadata_cache_usage) AS t
WHERE
  creation_time >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 3 DAY)
  AND (statement_type != 'SCRIPT' OR statement_type IS NULL)
ORDER BY
  creation_time DESC
LIMIT 50;
```

## Search Index Usage

Verify whether queries used a search index (`index_usage_mode` is `UNUSED`,
`PARTIALLY_USED`, or `FULLY_USED`) and diagnose why an index was not used.
`index_unused_reasons` is populated only for `UNUSED` and `PARTIALLY_USED`, so
the `LEFT JOIN` keeps `FULLY_USED` jobs in the result.

```sql
SELECT
  job_id,
  creation_time,
  total_slot_ms,
  total_bytes_processed,
  search_statistics.index_usage_mode,
  unused_reason.code AS unused_reason_code,
  unused_reason.base_table.table_id AS base_table_id,
  unused_reason.index_name
FROM
  `{project_id}`.`region-{region}`.INFORMATION_SCHEMA.JOBS_BY_PROJECT
LEFT JOIN
  UNNEST(search_statistics.index_unused_reasons) AS unused_reason
WHERE
  creation_time >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 3 DAY)
  AND search_statistics IS NOT NULL
ORDER BY
  creation_time DESC
LIMIT 50;
```

## Materialized View Rewrite Usage

Verify whether queries used a materialized view (`chosen`), including queries
that smart tuning rewrote from the base tables, and diagnose why a candidate
view was rejected (`rejected_reason`, for example `NO_DATA`, `COST`, or
`BASE_TABLE_DATA_CHANGE`). A view that is not listed in
`materialized_view_statistics` did not match the query shape. If many views are
considered, the list might be incomplete. Automatic refresh jobs have
`materialized_view_refresh` in the job ID, so the query excludes them; to see
refresh cost instead, query `JOBS_BY_PROJECT` in the view's project without the
`UNNEST`, filter on `job_id LIKE '%materialized_view_refresh_%'`, and read
`total_slot_ms`, `total_bytes_processed`, and
`materialized_view_statistics.materialized_view[SAFE_OFFSET(0)].rejected_reason`.

```sql
SELECT
  job_id,
  creation_time,
  total_slot_ms,
  total_bytes_processed,
  mv.table_reference.dataset_id AS mv_dataset_id,
  mv.table_reference.table_id AS mv_table_id,
  mv.chosen,
  mv.estimated_bytes_saved,
  mv.rejected_reason
FROM
  `{project_id}`.`region-{region}`.INFORMATION_SCHEMA.JOBS_BY_PROJECT,
  UNNEST(materialized_view_statistics.materialized_view) AS mv
WHERE
  creation_time >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 3 DAY)
  AND job_id NOT LIKE '%materialized_view_refresh_%'
ORDER BY
  creation_time DESC
LIMIT 50;
```

## Query Performance Variance & Outlier Discovery

Identify queries that experienced the highest execution variance compared to
their historical baseline duration (`avg_previous_execution_ms`).

```sql
SELECT
  job_id,
  user_email,
  reservation_id,
  creation_time,
  ROUND(TIMESTAMP_DIFF(end_time, start_time, MILLISECOND) / 1000.0, 1) AS duration_sec,
  ROUND(query_info.performance_insights.avg_previous_execution_ms / 1000.0, 1)
    AS baseline_avg_duration_sec,
  ROUND(
    SAFE_DIVIDE(
      TIMESTAMP_DIFF(end_time, start_time, MILLISECOND),
      query_info.performance_insights.avg_previous_execution_ms),
    2) AS variance_ratio,
  total_slot_ms,
  total_bytes_billed
FROM
  `{project_id}`.`region-{region}`.INFORMATION_SCHEMA.JOBS_BY_PROJECT
WHERE
  creation_time
    BETWEEN TIMESTAMP('{target_start_timestamp}')
    AND TIMESTAMP('{target_end_timestamp}')
  AND state = 'DONE'
  AND (statement_type != 'SCRIPT' OR statement_type IS NULL)
  AND query_info.performance_insights.avg_previous_execution_ms IS NOT NULL
ORDER BY
  variance_ratio DESC
LIMIT 50;
```

## Stage Row Expansion, Shuffle Spill & Join Insights

Unnest `job_stages` in `INFORMATION_SCHEMA.JOBS_BY_PROJECT` across recent jobs
(or filter by `job_id = '{job_id}'` for a single job) to detect join row
explosions (`records_written >> records_read` caused by missing `ON` conditions,
unintentional `CROSS JOIN`s, or non-selective/many-to-many join predicates),
shuffle spills to disk (`shuffle_output_bytes_spilled > 0`), worker scheduling
wait delays (`wait_ratio_avg`, `wait_ms_avg`), and engine-surfaced join/skew
insights (`high_cardinality_joins`, `partition_skew`). Note that `job_stages` is
empty for queries that read from tables with row-level access policies.

```sql
SELECT
  j.job_id,
  j.user_email,
  j.creation_time,
  j.total_slot_ms,
  stage.id AS stage_id,
  stage.name AS stage_name,
  stage.records_read,
  stage.records_written,
  ROUND(
    SAFE_DIVIDE(stage.records_written, NULLIF(stage.records_read, 0)), 2)
    AS row_expansion_ratio,
  stage.shuffle_output_bytes,
  stage.shuffle_output_bytes_spilled,
  stage.slot_ms AS stage_slot_ms,
  stage.wait_ratio_avg,
  stage.wait_ratio_max,
  stage.wait_ms_avg,
  stage.wait_ms_max,
  stage.compute_ratio_avg,
  stage.compute_ratio_max,
  stage.compute_ms_avg,
  stage.compute_ms_max,
  insight.slot_contention,
  insight.insufficient_shuffle_quota,
  insight.high_cardinality_joins,
  insight.partition_skew
FROM
  `{project_id}`.`region-{region}`.INFORMATION_SCHEMA.JOBS_BY_PROJECT AS j,
  UNNEST(j.job_stages) AS stage
LEFT JOIN
  UNNEST(
    j.query_info.performance_insights.stage_performance_standalone_insights)
    AS insight
  ON stage.id = insight.stage_id
WHERE
  j.creation_time >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 7 DAY)
  AND j.job_type = 'QUERY'
  AND j.state = 'DONE'
  AND (
    stage.records_written > stage.records_read * 10
    OR stage.shuffle_output_bytes_spilled > 0
    OR ARRAY_LENGTH(insight.high_cardinality_joins) > 0
    OR ARRAY_LENGTH(insight.partition_skew.skew_sources) > 0)
ORDER BY
  row_expansion_ratio DESC,
  stage.slot_ms DESC
LIMIT 50;
```
resource_contention_queries.md 9.3 KB
# Resource Contention Queries

Telemetry and SQL queries for diagnosing slot contention, tracking per-minute
and window-averaged concurrency timelines, comparing degraded vs baseline
timeframes, detecting noisy neighbor workload variance, and analyzing pending
job backlogs.

## Table of Contents

-   [Per-Minute Project Slot Usage, Concurrency & Queue Timeline](#per-minute-project-slot-usage-concurrency-queue-timeline)
    (Lines 17-48)
-   [Reservation Maximum Utilization & Slot Saturation Timeline (1-Second Resolution)](#reservation-maximum-utilization-slot-saturation-timeline-1-second-resolution)
    (Lines 49-250)
-   [Slot Contention & Queue Latency Diagnosis](#slot-contention-queue-latency-diagnosis)
    (Lines 251-280)

## Per-Minute Project Slot Usage, Concurrency & Queue Timeline

Groups by 1-minute buckets (`MINUTE`) to track concurrency, per project job
queue length, slot usage over time.

```sql
SELECT
  TIMESTAMP_TRUNC(period_start, MINUTE) AS window_minute,
  project_id AS resource_owner_project_id,
  reservation_id,
  ROUND(SUM(period_slot_ms) / 1000.0 / 60.0, 1) AS slot_usage,
  ROUND(COUNT(*) / 60.0, 1) AS job_concurrency,
  ROUND(COUNTIF(state = 'PENDING') / 60.0, 1) AS project_queue_length,
FROM
  `{project_id}`.`region-{region}`.INFORMATION_SCHEMA.JOBS_TIMELINE_BY_PROJECT
WHERE
  job_creation_time
    BETWEEN TIMESTAMP_SUB(TIMESTAMP('{target_start_timestamp}'), INTERVAL 2 DAY)
    AND TIMESTAMP('{target_end_timestamp}')
  AND period_start
    BETWEEN TIMESTAMP('{target_start_timestamp}')
    AND TIMESTAMP('{target_end_timestamp}')
  AND (statement_type != 'SCRIPT' OR statement_type IS NULL)
GROUP BY
  window_minute,
  resource_owner_project_id,
  reservation_id
ORDER BY
  window_minute DESC,
  slot_usage DESC;
```

## Reservation Maximum Utilization & Slot Saturation Timeline (1-Second Resolution)

Evaluates true reservation slot saturation by expanding reservation capacity and
job slot consumption to 1-second resolution. Evaluates the time-average
percentage of time a reservation spent at maximum capacity (> 95%), accounting
for primary vs. failover baseline slots, scaling mode headroom, and borrowed
idle slots.

```sql
WITH
  reservation_timeline_raw AS (
    SELECT
      max_slots,
      slots_assigned,
      autoscale,
      ignore_idle_slots,
      per_second_details,
      period_start,
      edition,
      project_id AS admin_project_id,
      reservation_id,
      scaling_mode,
      is_creation_region
    FROM
      `{admin_project_id}`.`region-{region}`.INFORMATION_SCHEMA.RESERVATIONS_TIMELINE_BY_PROJECT
    WHERE
      period_start
      BETWEEN TIMESTAMP('{target_start_timestamp}')
      AND TIMESTAMP('{target_end_timestamp}')
  ),
  reservation_per_second AS (
    SELECT
      s.start_time AS period_start,
      edition,
      admin_project_id,
      reservation_id,
      scaling_mode,
      ignore_idle_slots,
      -- Primary region baseline & autoscale headroom
      IF(is_creation_region, IFNULL(s.slots_assigned, 0), 0) AS baseline_slots,
      IF(
        is_creation_region,
        IF(
          scaling_mode IN ('ALL_SLOTS', 'AUTOSCALE_ONLY'),
          IFNULL(max_slots, 0) - IFNULL(s.slots_assigned, 0),
          0),
        0) AS max_slots_exclude_baseline,
      -- Failover secondary region baseline & autoscale headroom
      IF(NOT is_creation_region, IFNULL(s.slots_assigned, 0), 0) AS failover_baseline_slots,
      IF(
        NOT is_creation_region,
        IF(
          scaling_mode IN ('ALL_SLOTS', 'AUTOSCALE_ONLY'),
          IFNULL(max_slots, 0) - IFNULL(s.slots_assigned, 0),
          0),
        0) AS failover_max_slots_exclude_baseline,
      IFNULL(s.autoscale_current_slots, 0) AS autoscale_current_slots,
      IFNULL(s.autoscale_max_slots, 0) AS autoscale_max_slots,
      IFNULL(s.borrowed_slots, 0) AS borrowed_slots
    FROM
      reservation_timeline_raw,
      UNNEST(
        IF(
          ARRAY_LENGTH(per_second_details) > 0,
          ARRAY(
            SELECT AS STRUCT
              s.start_time,
              s.autoscale_current_slots,
              s.autoscale_max_slots,
              s.slots_assigned,
              s.borrowed_slots
            FROM
              UNNEST(per_second_details) AS s
          ),
          ARRAY(
            SELECT AS STRUCT
              s AS start_time,
              autoscale.current_slots AS autoscale_current_slots,
              autoscale.max_slots AS autoscale_max_slots,
              slots_assigned AS slots_assigned,
              0 AS borrowed_slots
            FROM
              UNNEST(
                GENERATE_TIMESTAMP_ARRAY(
                  period_start,
                  TIMESTAMP_ADD(period_start, INTERVAL 59 SECOND),
                  INTERVAL 1 SECOND)) AS s
          ))) AS s
  ),
  jobs_per_second AS (
    SELECT
      TIMESTAMP_TRUNC(period_start, SECOND) AS period_start,
      reservation_id,
      SUM(period_slot_ms) / 1000.0 AS used_slots,
      COUNT(*) AS job_concurrency,
      COUNTIF(state = 'PENDING') AS queued_job_concurrency,
      COUNT(DISTINCT project_id) AS project_concurrency
    FROM
      `{project_id}`.`region-{region}`.INFORMATION_SCHEMA.JOBS_TIMELINE_BY_ORGANIZATION
    WHERE
      job_creation_time
        BETWEEN TIMESTAMP_SUB(TIMESTAMP('{target_start_timestamp}'), INTERVAL 2 DAY)
        AND TIMESTAMP('{target_end_timestamp}')
      AND period_start
        BETWEEN TIMESTAMP('{target_start_timestamp}')
        AND TIMESTAMP('{target_end_timestamp}')
      AND (statement_type != 'SCRIPT' OR statement_type IS NULL)
    GROUP BY
      period_start,
      reservation_id
  ),
  reservation_job_joined AS (
    SELECT
      r.period_start,
      r.reservation_id,
      r.edition,
      r.scaling_mode,
      r.ignore_idle_slots,
      r.baseline_slots,
      r.failover_baseline_slots,
      r.autoscale_max_slots,
      r.max_slots_exclude_baseline,
      r.failover_max_slots_exclude_baseline,
      r.autoscale_current_slots,
      r.borrowed_slots AS idle_slots,
      IFNULL(j.used_slots, 0) AS total_slot_usage,
      IFNULL(j.job_concurrency, 0) AS job_concurrency,
      IFNULL(j.queued_job_concurrency, 0) AS queued_job_concurrency,
      IFNULL(j.project_concurrency, 0) AS project_concurrency,
      -- Total maximum slot capacity ceiling across baseline, autoscale, and failover
      (
        r.baseline_slots
        + r.failover_baseline_slots
        + r.autoscale_max_slots
        + r.max_slots_exclude_baseline
        + r.failover_max_slots_exclude_baseline) AS total_max_capacity,
      -- Attribution of used slots across baseline, autoscale, and idle pools
      GREATEST(
        LEAST(
          r.baseline_slots + r.failover_baseline_slots, IFNULL(j.used_slots, 0) - r.borrowed_slots),
        0) AS baseline_used_slots,
      LEAST(
        GREATEST(
          IFNULL(j.used_slots, 0)
            - r.borrowed_slots
            - (r.baseline_slots + r.failover_baseline_slots),
          0),
        r.autoscale_current_slots) AS autoscaled_used_slots
    FROM
      reservation_per_second r
    LEFT JOIN
      jobs_per_second j
      USING (period_start, reservation_id)
  ),
  second_level_metrics AS (
    SELECT
      period_start,
      reservation_id,
      edition,
      scaling_mode,
      ignore_idle_slots,
      total_slot_usage,
      baseline_slots + failover_baseline_slots AS total_baseline_capacity,
      total_max_capacity,
      idle_slots,
      baseline_used_slots,
      autoscaled_used_slots,
      job_concurrency,
      queued_job_concurrency,
      project_concurrency,
      -- Saturation Indicator: True when active slot usage exceeds 95% of total maximum capacity
      IF(
        SAFE_DIVIDE(
          idle_slots + baseline_used_slots + autoscaled_used_slots,
          total_max_capacity)
          > 0.95,
        1,
        0) AS is_max_utilization
    FROM
      reservation_job_joined
  )
SELECT
  TIMESTAMP_TRUNC(period_start, MINUTE) AS window_minute,
  reservation_id,
  -- Time-average percentage of seconds spent at max capacity (> 95%) during the minute
  ROUND(AVG(is_max_utilization) * 100, 1) AS pct_time_at_max_utilization,
  ROUND(SUM(total_slot_usage) / 60, 1) AS avg_slot_usage,
  ROUND(AVG(total_baseline_capacity), 1) AS avg_baseline_capacity,
  ROUND(AVG(total_max_capacity), 1) AS avg_max_capacity,
  ROUND(AVG(idle_slots), 1) AS avg_borrowed_idle_slots,
  ROUND(AVG(queued_job_concurrency), 1) AS avg_queued_jobs,
  ROUND(AVG(job_concurrency), 1) AS avg_job_concurrency
FROM
  second_level_metrics
GROUP BY
  window_minute,
  reservation_id
ORDER BY
  window_minute DESC,
  pct_time_at_max_utilization DESC;
```

## Slot Contention & Queue Latency Diagnosis

Identify completed queries that experienced excessive queuing latency between
`creation_time` and `start_time` due to lack of available slots.

```sql
SELECT
  job_id,
  user_email,
  creation_time,
  start_time,
  TIMESTAMP_DIFF(start_time, creation_time, SECOND) AS queue_latency_sec,
  TIMESTAMP_DIFF(end_time, start_time, SECOND) AS execution_duration_sec,
  total_slot_ms,
  reservation_id,
  (
    SELECT LOGICAL_OR(slot_contention)
    FROM UNNEST(query_info.performance_insights.stage_performance_standalone_insights)
  ) AS has_slot_contention
FROM
  `{project_id}`.`region-{region}`.INFORMATION_SCHEMA.JOBS_BY_PROJECT
WHERE
  creation_time >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 2 DAY)
  AND state = 'DONE'
  AND (statement_type != 'SCRIPT' OR statement_type IS NULL)
  AND TIMESTAMP_DIFF(start_time, creation_time, SECOND) > 5
ORDER BY
  queue_latency_sec DESC
LIMIT 50;
```
schema_compute.md 42.0 KB
# BigQuery Compute & Capacity INFORMATION_SCHEMA Reference

A comprehensive dictionary, column definition guide, and physical unit
specification for all Compute, Job, Session, Reservation, Capacity Commitment,
and Assignment views in BigQuery `INFORMATION_SCHEMA`.

## Table of Contents

-   [View Scoping & Qualification Matrix](#view-scoping-qualification-matrix)
    (Lines 38-57)
-   [1. Jobs & Compute Telemetry Views](#1-jobs-compute-telemetry-views) (Lines
    58-269)
    -   [`INFORMATION_SCHEMA.JOBS` (and `_BY_PROJECT`, `_BY_ORGANIZATION`, `_BY_USER`, `_BY_FOLDER`)](#information_schemajobs-and-_by_project-_by_organization-_by_user-_by_folder)
        (Lines 60-177)
    -   [`INFORMATION_SCHEMA.JOBS_TIMELINE` (and `_BY_PROJECT`, `_BY_ORGANIZATION`, `_BY_USER`, `_BY_FOLDER`)](#information_schemajobs_timeline-and-_by_project-_by_organization-_by_user-_by_folder)
        (Lines 178-234)
    -   [`INFORMATION_SCHEMA.SESSIONS_BY_USER` (and `_BY_PROJECT`)](#information_schemasessions_by_user-and-_by_project)
        (Lines 235-269)
-   [2. Capacity, Reservations & Commitments Views](#2-capacity-reservations-commitments-views)
    (Lines 270-594)
    -   [`INFORMATION_SCHEMA.RESERVATIONS` (and `_BY_PROJECT`)](#information_schemareservations-and-_by_project)
        (Lines 272-311)
    -   [`INFORMATION_SCHEMA.RESERVATION_CHANGES` (and `_BY_PROJECT`)](#information_schemareservation_changes-and-_by_project)
        (Lines 312-355)
    -   [`INFORMATION_SCHEMA.RESERVATIONS_TIMELINE` (and `_BY_PROJECT`)](#information_schemareservations_timeline-and-_by_project)
        (Lines 356-429)
    -   [`INFORMATION_SCHEMA.CAPACITY_COMMITMENTS` (and `_BY_PROJECT`)](#information_schemacapacity_commitments-and-_by_project)
        (Lines 430-460)
    -   [`INFORMATION_SCHEMA.CAPACITY_COMMITMENT_CHANGES_BY_PROJECT` (and `_CHANGES`)](#information_schemacapacity_commitment_changes_by_project-and-_changes)
        (Lines 461-499)
    -   [`INFORMATION_SCHEMA.ASSIGNMENTS` (and `_BY_PROJECT`)](#information_schemaassignments-and-_by_project)
        (Lines 500-531)
    -   [`INFORMATION_SCHEMA.ASSIGNMENT_CHANGES_BY_PROJECT` (and `_CHANGES`)](#information_schemaassignment_changes_by_project-and-_changes)
        (Lines 532-567)
    -   [`INFORMATION_SCHEMA.BI_CAPACITIES` (and `BI_CAPACITY_CHANGES`)](#information_schemabi_capacities-and-bi_capacity_changes)
        (Lines 568-594)

## View Scoping & Qualification Matrix

BigQuery Compute and Capacity views are **Region-Only** scoped. They require the
`region-{region}` dataset qualifier (e.g.
`` `{project_id}`.`region-{region}`.INFORMATION_SCHEMA.{view_name}``) and cannot
be scoped to a single dataset:

<!-- mdformat off -->
| View Family | INFORMATION_SCHEMA View(s) | Qualification Scope | Syntax Pattern & Scoping Rules |
| :--- | :--- | :--- | :--- |
| **Jobs & Scripts** | `JOBS*` (`_BY_PROJECT`, `_BY_USER`, `_BY_FOLDER`, `_BY_ORGANIZATION`) | **Region-Only** | `` `{project_id}`.`region-{region}`.INFORMATION_SCHEMA.JOBS*``<br>• Real-time & historical job metadata (180 days retention).<br>• `_BY_USER` variant requires least privilege (`roles/bigquery.user`). |
| **Job Timeline** | `JOBS_TIMELINE*` (`_BY_PROJECT`, `_BY_USER`, `_BY_FOLDER`, `_BY_ORGANIZATION`) | **Region-Only** | `` `{project_id}`.`region-{region}`.INFORMATION_SCHEMA.JOBS_TIMELINE*``<br>• 1-second continuous slot time-series slices for fine-grained workload profiling. |
| **SQL Sessions** | `SESSIONS_BY_USER`, `SESSIONS_BY_PROJECT` | **Region-Only** | `` `{project_id}`.`region-{region}`.INFORMATION_SCHEMA.SESSIONS*``<br>• Active and interactive multi-statement SQL sessions and notebook lifetimes. |
| **Reservations** | `RESERVATIONS*`, `RESERVATION_CHANGES*` | **Region-Only** | `` `{project_id}`.`region-{region}`.INFORMATION_SCHEMA.RESERVATIONS*``<br>• Current baseline slot limits, edition tier bindings, and reservation lifecycle changes (`RESERVATION_CHANGES`). |
| **Reservation Timeline** | `RESERVATIONS_TIMELINE*` (`_BY_PROJECT`) | **Region-Only** | `` `{project_id}`.`region-{region}`.INFORMATION_SCHEMA.RESERVATIONS_TIMELINE*``<br>• 1-minute discrete timeline of assigned baseline slots and periodic autoscale slot-seconds (`period_autoscale_slot_seconds`). Retention is 180 days. |
| **Capacity Commitments** | `CAPACITY_COMMITMENTS*`, `CAPACITY_COMMITMENT_CHANGES*` | **Region-Only** | `` `{project_id}`.`region-{region}`.INFORMATION_SCHEMA.CAPACITY_COMMITMENTS*``<br>• 1-Year / 3-Year commitment purchases, active states, renewal plans, and lifecycle changes (`CAPACITY_COMMITMENT_CHANGES`). |
| **Workload Assignments** | `ASSIGNMENTS*`, `ASSIGNMENT_CHANGES*` | **Region-Only** | `` `{project_id}`.`region-{region}`.INFORMATION_SCHEMA.ASSIGNMENTS*``<br>• Mapping of projects/folders/orgs to specific reservations (`assignee_id`, `job_type`) and assignment lifecycle changes. |
| **BI Engine Capacities** | `BI_CAPACITIES`, `BI_CAPACITY_CHANGES` | **Region-Only** | `` `{project_id}`.`region-{region}`.INFORMATION_SCHEMA.BI_CAPACITIES``<br>• BI Engine RAM allocation sizes (bytes) and preferred table routing rules (`BI_CAPACITY_CHANGES` for update logs). |
<!-- mdformat on -->

## 1. Jobs & Compute Telemetry Views

### `INFORMATION_SCHEMA.JOBS` (and `_BY_PROJECT`, `_BY_ORGANIZATION`, `_BY_USER`, `_BY_FOLDER`)

#### High-Level Description

Provides real-time and historical metadata for all query, load, extract, and
copy jobs executed in the project or organization. Contains critical compute
telemetry including bytes billed, execution durations, slot consumption,
parent-child script hierarchy, and error classifications. Retention is 180 days.

#### Required IAM Permissions & Predefined Roles

*   **`JOBS_BY_USER` (Least Privilege):** Requires `bigquery.jobs.list` on the
    project. Granted by **BigQuery User** (`roles/bigquery.user`) or **BigQuery
    Admin** (`roles/bigquery.admin`).
*   **`JOBS` / `JOBS_BY_PROJECT`:** Requires `bigquery.jobs.listAll` on the
    project. Granted by **BigQuery Resource Admin**
    (`roles/bigquery.resourceAdmin`), **BigQuery Resource Editor**
    (`roles/bigquery.resourceEditor`), **BigQuery Resource Viewer**
    (`roles/bigquery.resourceViewer`), **BigQuery Studio Admin**
    (`roles/bigquery.studioAdmin`), or **BigQuery Admin**
    (`roles/bigquery.admin`).
*   **`JOBS_BY_FOLDER`:** Requires `bigquery.jobs.listAll` on the parent folder.
*   **`JOBS_BY_ORGANIZATION`:** Requires `bigquery.jobs.listAll` on the
    organization.

<!-- mdformat off -->
| Column Name | Data Type | Physical Unit | Description & Conversion Formula |
| :--- | :--- | :--- | :--- |
| `bi_engine_statistics` | `RECORD` | Struct | BI Engine execution mode (`bi_engine_mode`, `acceleration_mode`, `bi_engine_reasons`). |
| `cache_hit` | `BOOLEAN` | Boolean | `TRUE` if query results were served from deterministic cache (0 billed bytes). |
| `continuous` | `BOOLEAN` | Boolean | Whether the job is a continuous query. |
| `continuous_query_info.output_watermark` | `TIMESTAMP` | UTC Timestamp | Point up to which continuous query has successfully processed data. |
| `creation_time` | `TIMESTAMP` | UTC Timestamp | (Partitioning column) Job submission timestamp in UTC. Pad by `-2 / +1` days relative to target PST billing window for partition pruning. |
| `destination_table` | `RECORD` | Struct | Destination table reference (`project_id`, `dataset_id`, `table_id`). |
| `dml_statistics` | `RECORD` | Struct | DML row modifications (`inserted_row_count`, `deleted_row_count`, `updated_row_count`). Only in `_BY_PROJECT`, `_BY_USER`, `_BY_FOLDER`. |
| `edition` | `STRING` | Enum | Edition tier executing the job (`'STANDARD'`, `'ENTERPRISE'`, `'ENTERPRISE_PLUS'`). |
| `end_time` | `TIMESTAMP` | UTC Timestamp | Timestamp when job completed execution (`DONE` state). Used for PST billing alignment: `EXTRACT(DATE FROM end_time AT TIME ZONE 'PST8PDT')`. |
| `error_result` | `RECORD` | Struct | Job failure details (`reason`, `location`, `message`). Query is billable if `error_result IS NULL OR error_result.reason = 'stopped'`. |
| `external_service_costs` | `ARRAY<RECORD>` | Struct Array | Array of external service costs incurred by the query job. |
| `folder_numbers` | `ARRAY<INT64>` | Array | Folder hierarchy IDs containing the project (only populated in `JOBS_BY_FOLDER`). |
| `job_creation_reason.code` | `STRING` | Enum | High-level job creation reason: `'REQUESTED'`, `'LONG_RUNNING'`, `'LARGE_RESULTS'`, `'OTHER'`. |
| `job_id` | `STRING` | UUID | Unique job identifier within project and region (e.g. `bquxjob_1234`). |
| `job_stages` | `ARRAY<RECORD>` | Struct Array | Query execution plan stages, read/compute/write ratios, records read, and shuffle spill statistics. Empty for queries that read from tables with row-level access policies. |
| `job_type` | `STRING` | Enum | Job type: `'QUERY'`, `'LOAD'`, `'EXTRACT'`, `'COPY'`, or `NULL` (background job). |
| `labels` | `ARRAY<RECORD>` | Struct Array | Key-value labels applied to the job for cost attribution. |
| `materialized_view_statistics` | `RECORD` | Struct | Statistics of materialized views considered and chosen for query rewrite. |
| `metadata_cache_statistics` | `RECORD` | Struct | Statistics for metadata column index usage on external tables. |
| `parent_job_id` | `STRING` | UUID | Job ID of parent multi-statement query script or workflow. |
| `priority` | `STRING` | Enum | Scheduling priority: `'INTERACTIVE'` or `'BATCH'`. |
| `principal_subject` | `STRING` | Principal | IAM principal subject string identity. |
| `project_id` | `STRING` | Project ID | (Clustering column) GCP project ID that submitted and was billed for the job. |
| `project_number` | `INT64` | Numeric ID | GCP project number. |
| `query` | `STRING` | SQL String | Raw SQL query text (available in `_BY_PROJECT` and `_BY_USER`). |
| `query_dialect` | `STRING` | Enum | Dialect used: `'GOOGLE_SQL'`, `'LEGACY_SQL'`, `'DEFAULT_LEGACY_SQL'`, `'DEFAULT_GOOGLE_SQL'`. |
| `query_info.optimization_details` | `RECORD` | Struct | History-based optimizations applied to the job (only in `JOBS_BY_PROJECT`). |
| `query_info.performance_insights` | `RECORD` | Struct | Optimization opportunities surfaced by the engine (e.g. Stage Performance, Join Spill). |
| `query_info.query_hashes.normalized_literals` | `STRING` | Hash String | Abstract query signature with literal values stripped. Used to group identical recurring query templates. |
| `query_info.resource_warning` | `STRING` | Warning | System warning if resource usage during query processing exceeded internal thresholds. |
| `referenced_tables` | `ARRAY<RECORD>` | Struct Array | List of all base tables, views, and external assets referenced by query (`project_id`, `dataset_id`, `table_id`). |
| `reservation_id` | `STRING` | Resource Path | Capacity reservation path (`ADMIN_PROJECT:LOCATION.RESERVATION_NAME`). `NULL` for on-demand queries. |
| `reservation_group_path` | `ARRAY<STRING>` | Array | Hierarchical reservation group path (e.g. `['my-group']`). |
| `search_statistics` | `RECORD` | Struct | Statistics for search queries utilizing search indexes. |
| `session_info` | `RECORD` | Struct | Multi-query session context (`session_id`). |
| `start_time` | `TIMESTAMP` | UTC Timestamp | Timestamp when compute resources transitioned from `PENDING` to `RUNNING`. |
| `state` | `STRING` | Enum | Lifecycle execution state: `'PENDING'`, `'RUNNING'`, `'DONE'`. |
| `statement_type` | `STRING` | Enum | SQL statement category (e.g. `'SELECT'`, `'CREATE_MODEL'`, `'SCRIPT'`, `'INSERT'`, `'UPDATE'`, `'DELETE'`). |
| `timeline` | `ARRAY<RECORD>` | Struct Array | Slice-level stage progression snapshots (`elapsed_ms`, `total_slot_ms`, `pending_units`, `completed_units`, `active_units`). |
| `total_bytes_billed` | `INT64` | **Bytes** | Raw billable bytes. **Formula to convert to TB:** `(total_bytes_billed / POWER(1024, 4)) * CASE statement_type WHEN 'CREATE_MODEL' THEN 50 ELSE 1 END`. Returns `NULL` if Row-Level Security (RLS) is active. |
| `total_bytes_processed` | `INT64` | **Bytes** | Total uncompressed bytes scanned after partition/column pruning. Returns `NULL` if Row-Level Security (RLS) is active. |
| `total_modified_partitions` | `INT64` | Count | Number of distinct table partitions updated by DML or load job. |
| `total_services_sku_slot_ms` | `INT64` | **Slot-ms** | Slot-ms consumed by external service workloads billed on the Services SKU. |
| `total_slot_ms` | `INT64` | **Slot-ms** | Total slot compute time consumed across entire duration including retries. **Formula for Slot-Hours:** `total_slot_ms / 1000.0 / 3600.0`. |
| `transaction_id` | `STRING` | UUID | Transaction ID in which this job ran, if any. |
| `transferred_bytes` | `INT64` | **Bytes** | Network egress/ingress bytes for BigQuery Omni and cross-region queries. |
| `user_email` | `STRING` | Email | (Clustering column) Email address or service account of the user who ran the job. |
| `vector_search_statistics` | `RECORD` | Struct | Statistics for vector search queries. |
<!-- mdformat on -->

#### Nested `job_stages` Schema (Field in `JOBS`)

The `job_stages` column in `JOBS` is an `ARRAY<RECORD>` where each element
represents a discrete execution stage (Input, Compute, Shuffle, Join, Output) in
the query plan (note that `job_stages` is empty for queries that read from
tables with row-level access policies):

*   `id` (`INT64`): Unique 0-indexed execution stage identifier.
*   `name` (`STRING`): Stage identifier (e.g. `'S00: Input'`,
    `'S01: Aggregate'`).
*   `input_stages` (`ARRAY<INT64>`): Stage IDs whose outputs feed into this
    stage.
*   `start_ms` (`INT64`): Millisecond timestamp when the stage began.
*   `end_ms` (`INT64`): Millisecond timestamp when the stage completed.
*   `slot_ms` (`INT64`): Slot compute time consumed by this stage.
*   `shuffle_output_bytes` (`INT64`): Bytes written to distributed shuffle.
*   `shuffle_output_bytes_spilled` (`INT64`): Bytes spilled to disk due to
    shuffle RAM pressure.
*   `records_read` (`INT64`): Number of input records consumed.
*   `records_written` (`INT64`): Number of output records produced.
*   `parallel_inputs` (`INT64`): Maximum parallel worker shards allocated.
*   `completed_parallel_inputs` (`INT64`): Shards successfully finished.
*   `wait_ratio_avg`, `wait_ratio_max` (`FLOAT64`): Fraction (`0.0-1.0`) of time
    the average or slowest worker in the stage spent waiting to be scheduled on
    available slots relative to the longest time any worker in any stage spent
    in any phase.
*   `wait_ms_avg`, `wait_ms_max` (`INT64`): Milliseconds the average or slowest
    worker in the stage spent waiting to be scheduled on available slots.
*   `read_ratio_avg`, `read_ratio_max`, `read_ms_avg`, `read_ms_max` (`FLOAT64`
    / `INT64`): Relative ratio and duration (ms) workers spent reading input
    table or shuffle data.
*   `compute_ratio_avg`, `compute_ratio_max`, `compute_ms_avg`, `compute_ms_max`
    (`FLOAT64` / `INT64`): Relative ratio and duration (ms) workers spent in CPU
    computation.
*   `write_ratio_avg`, `write_ratio_max`, `write_ms_avg`, `write_ms_max`
    (`FLOAT64` / `INT64`): Relative ratio and duration (ms) workers spent
    writing intermediate shuffle or final output data.
*   `status` (`STRING`): `'COMPLETE'`, `'RUNNING'`, `'FAILED'`, `'CANCELLED'`.
*   `steps` (`ARRAY<RECORD>`): Pipeline operations (`kind`, `substeps`).

### `INFORMATION_SCHEMA.JOBS_TIMELINE` (and `_BY_PROJECT`, `_BY_ORGANIZATION`, `_BY_USER`, `_BY_FOLDER`)

#### High-Level Description

Exposes fine-grained 1-second continuous telemetry for running BigQuery jobs.
Tracks instantaneous slot utilization, shuffle memory pressure, and concurrency
queue depth. Ideal for diagnosing latency spikes, scheduler throttling, and slot
starvation.

#### Required IAM Permissions & Predefined Roles

*   **`JOBS_TIMELINE_BY_USER` (Least Privilege):** Requires `bigquery.jobs.list`
    on the project. Granted by **BigQuery User** (`roles/bigquery.user`) or
    **BigQuery Admin** (`roles/bigquery.admin`).
*   **`JOBS_TIMELINE` / `JOBS_TIMELINE_BY_PROJECT`:** Requires
    `bigquery.jobs.listAll` on the project. Granted by **BigQuery Resource
    Admin** (`roles/bigquery.resourceAdmin`), **BigQuery Resource Editor**
    (`roles/bigquery.resourceEditor`), **BigQuery Resource Viewer**
    (`roles/bigquery.resourceViewer`), **BigQuery Studio Admin**
    (`roles/bigquery.studioAdmin`), or **BigQuery Admin**
    (`roles/bigquery.admin`).
*   **`JOBS_TIMELINE_BY_FOLDER`:** Requires `bigquery.jobs.listAll` on the
    parent folder.
*   **`JOBS_TIMELINE_BY_ORGANIZATION`:** Requires `bigquery.jobs.listAll` on the
    organization.

<!-- mdformat off -->
| Column Name | Data Type | Physical Unit | Description & Conversion Formula |
| :--- | :--- | :--- | :--- |
| `cache_hit` | `BOOLEAN` | Boolean | Whether query results were served from cache. |
| `edition` | `STRING` | Enum | Target Edition tier (`'STANDARD'`, `'ENTERPRISE'`, `'ENTERPRISE_PLUS'`). |
| `error_result` | `RECORD` | Struct | Details of error (if any) as an `ErrorProto` (`reason`, `location`, `message`). |
| `job_creation_time` | `TIMESTAMP` | UTC Timestamp | (Partitioning column) Timestamp when job was submitted in UTC. |
| `job_end_time` | `TIMESTAMP` | UTC Timestamp | Timestamp when job completed execution. |
| `job_id` | `STRING` | UUID | Unique job identifier (e.g. `bquxjob_1234`). |
| `job_start_time` | `TIMESTAMP` | UTC Timestamp | Timestamp when compute resources began execution. |
| `job_type` | `STRING` | Enum | `'QUERY'`, `'LOAD'`, `'EXTRACT'`, `'COPY'`, or `NULL` (background). |
| `labels` | `ARRAY<RECORD>` | Struct Array | Array of key-value labels applied to the job. |
| `parent_job_id` | `STRING` | UUID | ID of the parent multi-statement query script, if any. |
| `period_estimated_runnable_units` | `INT64` | Count | Number of worker units ready to execute immediately but queued waiting for available slots. |
| `period_shuffle_ram_usage_ratio` | `FLOAT64` | Ratio (0.0–1.0) | Peak shuffle RAM utilization ratio during slice (0.0 if running on autoscaling with 0 baseline slots). |
| `period_slot_ms` | `INT64` | **Slot-ms** | Compute consumed within this 1-second slice. **Instantaneous Slots:** `period_slot_ms / 1000.0`. |
| `period_start` | `TIMESTAMP` | UTC Timestamp | Start time of this 1-second interval. |
| `principal_subject` | `STRING` | Principal | IAM principal subject string representation. |
| `priority` | `STRING` | Enum | Job scheduling priority: `'INTERACTIVE'` or `'BATCH'`. |
| `project_id` | `STRING` | Project ID | (Clustering column) ID of the project submitting the job. |
| `project_number` | `INT64` | Numeric ID | Numeric project number. |
| `reservation_group_path` | `ARRAY<STRING>` | Array | Hierarchical reservation group path (e.g. `['my-group']`). |
| `reservation_id` | `STRING` | Resource Path | Name of primary reservation assigned to job at end of period (`ADMIN_PROJECT:LOCATION.RESERVATION_NAME`). |
| `state` | `STRING` | Enum | Running state of the job at end of slice: `'PENDING'`, `'RUNNING'`, `'DONE'`. |
| `statement_type` | `STRING` | Enum | Statement category (e.g. `'SELECT'`, `'INSERT'`, `'UPDATE'`, `'DELETE'`). |
| `total_bytes_billed` | `INT64` | **Bytes** | Cumulative bytes billed by job up to slice (populated for completed jobs). |
| `total_bytes_processed` | `INT64` | **Bytes** | Cumulative bytes processed by job up to slice. |
| `transaction_id` | `STRING` | UUID | ID of the transaction in which this job ran, if any. |
| `user_email` | `STRING` | Email | (Clustering column) Email address or service account of the user who ran the job. |
<!-- mdformat on -->

### `INFORMATION_SCHEMA.SESSIONS_BY_USER` (and `_BY_PROJECT`)

#### High-Level Description

Lists multi-statement and interactive notebook sessions created by users and
service accounts. Tracks active session IDs, session lifetimes, and temporary
table allocations.

#### Required IAM Permissions & Predefined Roles

*   **`SESSIONS_BY_USER` (Least Privilege):** Requires `bigquery.jobs.list` on
    the project. Granted by **BigQuery User** (`roles/bigquery.user`) or
    **BigQuery Admin** (`roles/bigquery.admin`).
*   **`SESSIONS_BY_PROJECT`:** Requires `bigquery.jobs.listAll` on the project.
    Granted by **BigQuery Resource Viewer** (`roles/bigquery.resourceViewer`),
    **BigQuery Resource Editor** (`roles/bigquery.resourceEditor`), **BigQuery
    Resource Admin** (`roles/bigquery.resourceAdmin`), or **BigQuery Admin**
    (`roles/bigquery.admin`).

<!-- mdformat off -->
| Column Name | Data Type | Physical Unit | Description |
| :--- | :--- | :--- | :--- |
| `session_id` | `STRING` | ID String | Unique session identifier. |
| `project_id` | `STRING` | Project ID | Project hosting the session. |
| `project_number` | `INT64` | Numeric ID | Numeric project identifier. |
| `user_email` | `STRING` | Email | User identity who initiated the session. |
| `principal_subject` | `STRING` | Principal | IAM principal subject. |
| `is_active` | `BOOLEAN` | Boolean | `TRUE` if the session is currently active and can receive new statements. |
| `creation_time` | `TIMESTAMP` | UTC Timestamp | Timestamp when the session was created. |
| `expiration_time` | `TIMESTAMP` | UTC Timestamp | Timestamp when the session expires and temp tables are dropped. |
| `last_modified_time` | `TIMESTAMP` | UTC Timestamp | Timestamp of the most recent query in this session. |
<!-- mdformat on -->

<a id="sec-reservations"></a>

## 2. Capacity, Reservations & Commitments Views

### `INFORMATION_SCHEMA.RESERVATIONS` (and `_BY_PROJECT`)

#### High-Level Description

Contains a near real-time list of all capacity reservations in the
administration project, including baseline slot allocations, autoscale limits,
Edition tiers, scaling modes, and disaster recovery replica locations.

#### Required IAM Permissions & Predefined Roles

*   Requires `bigquery.reservations.list` on the administration project.
*   **Predefined Roles:** **BigQuery Resource Admin**
    (`roles/bigquery.resourceAdmin`), **BigQuery Resource Editor**
    (`roles/bigquery.resourceEditor`), **BigQuery Resource Viewer**
    (`roles/bigquery.resourceViewer`), **BigQuery User**
    (`roles/bigquery.user`), or **BigQuery Admin** (`roles/bigquery.admin`).

<!-- mdformat off -->
| Column Name | Data Type | Physical Unit | Description |
| :--- | :--- | :--- | :--- |
| `autoscale.current_slots` | `INT64` | **Slots** | Real-time dynamically provisioned autoscale slots added to reservation. |
| `autoscale.max_slots` | `INT64` | **Slots** | Maximum configured autoscale slot ceiling. |
| `ddl` | `STRING` | SQL String | GoogleSQL DDL statement used to create this reservation. |
| `edition` | `STRING` | Enum | Edition tier: `'STANDARD'`, `'ENTERPRISE'`, `'ENTERPRISE_PLUS'`. |
| `ignore_idle_slots` | `BOOLEAN` | Boolean | When `FALSE`, reservation can borrow unused idle slots from other commitments. |
| `labels` | `ARRAY<RECORD>` | Struct Array | Array of key-value labels associated with the reservation. |
| `max_slots` | `INT64` | **Slots** | Total maximum slot limit (baseline + idle + autoscale) for reservation predictability. |
| `original_primary_location` | `STRING` | Region | Region where the reservation was originally created (for Disaster Recovery). |
| `primary_location` | `STRING` | Region | Current location of reservation's primary replica in Disaster Recovery. |
| `project_id` | `STRING` | Project ID | ID of the reservation administration project. |
| `project_number` | `INT64` | Numeric ID | Number of the administration project. |
| `reservation_group_path` | `ARRAY<STRING>` | Array | Reservation group hierarchy path (e.g. `['my-group']`). |
| `reservation_name` | `STRING` | Resource Path | User-provided reservation name. |
| `scaling_mode` | `STRING` | Enum | Scaling mode determining progression from baseline to `max_slots` (`'ALL_SLOTS'`, `'IDLE_SLOTS_ONLY'`, `'AUTOSCALE_ONLY'`, `'SCALING_MODE_UNSPECIFIED'`). |
| `scheduling_policy` | `RECORD` | Struct | Default per-project caps within the reservation (`max_slots`, `concurrency`), or `NULL` if unset (Preview / feature-flag gated; verify availability with `SELECT * ... LIMIT 0` before projecting explicitly). |
| `secondary_location` | `STRING` | Region | Current location of reservation's secondary replica in Disaster Recovery. |
| `slot_capacity` | `INT64` | **Slots** | Baseline slot capacity configured for the reservation. |
| `target_job_concurrency` | `INT64` | Count | Target maximum concurrent queries before queueing (0 = dynamic auto-concurrency). |
<!-- mdformat on -->

### `INFORMATION_SCHEMA.RESERVATION_CHANGES` (and `_BY_PROJECT`)

#### High-Level Description

Contains a near real-time audit log of all changes made to reservations within
the administration project (creation, modification of baseline/autoscale, and
deletion). This view contains current reservations and deleted reservations
(deleted reservations are kept for a maximum of 41 days after which they are
removed from the view).

#### Required IAM Permissions & Predefined Roles

*   Requires `bigquery.reservations.list` on the administration project.
*   **Predefined Roles:** **BigQuery Resource Admin**
    (`roles/bigquery.resourceAdmin`), **BigQuery Resource Editor**
    (`roles/bigquery.resourceEditor`), **BigQuery Resource Viewer**
    (`roles/bigquery.resourceViewer`), **BigQuery User**
    (`roles/bigquery.user`), or **BigQuery Admin** (`roles/bigquery.admin`).

<!-- mdformat off -->
| Column Name | Data Type | Physical Unit | Description |
| :--- | :--- | :--- | :--- |
| `action` | `STRING` | Enum | Event action type: `'CREATE'`, `'UPDATE'`, `'DELETE'`. |
| `autoscale.current_slots` | `INT64` | **Slots** | Number of autoscale slots added to reservation at event time. |
| `autoscale.max_slots` | `INT64` | **Slots** | Maximum configured autoscale slot ceiling at event time. |
| `change_timestamp` | `TIMESTAMP` | UTC Timestamp | Timestamp when the reservation modification occurred. |
| `edition` | `STRING` | Enum | Edition tier: `'STANDARD'`, `'ENTERPRISE'`, `'ENTERPRISE_PLUS'`. |
| `ignore_idle_slots` | `BOOLEAN` | Boolean | Slot sharing status (`FALSE` allows borrowing idle capacity). |
| `labels` | `ARRAY<RECORD>` | Struct Array | Array of key-value labels associated with the reservation. |
| `max_slots` | `INT64` | **Slots** | Maximum slot limit for reservation predictability. |
| `original_primary_location` | `STRING` | Region | Location where reservation was originally created. |
| `primary_location` | `STRING` | Region | Location of primary replica in Disaster Recovery. |
| `project_id` | `STRING` | Project ID | ID of the administration project. |
| `project_number` | `INT64` | Numeric ID | Number of the administration project. |
| `reservation_group_path` | `ARRAY<STRING>` | Array | Reservation group hierarchy path. |
| `reservation_name` | `STRING` | Resource Path | User-provided reservation name. |
| `scaling_mode` | `STRING` | Enum | Scaling mode (`'ALL_SLOTS'`, `'IDLE_SLOTS_ONLY'`, `'AUTOSCALE_ONLY'`, `'SCALING_MODE_UNSPECIFIED'`). |
| `scheduling_policy` | `RECORD` | Struct | Default per-project caps within the reservation (`max_slots`, `concurrency`), or `NULL` if unset (Preview / feature-flag gated; verify availability with `SELECT * ... LIMIT 0` before projecting explicitly). |
| `secondary_location` | `STRING` | Region | Location of secondary replica in Disaster Recovery. |
| `slot_capacity` | `INT64` | **Slots** | Baseline slot capacity configured at event time. |
| `target_job_concurrency` | `INT64` | Count | Target query concurrency limit. |
| `user_email` | `STRING` | Email | Administrator or service identity who initiated the change (`'google'` if automated; `NULL` if unknown). |
<!-- mdformat on -->

### `INFORMATION_SCHEMA.RESERVATIONS_TIMELINE` (and `_BY_PROJECT`)

#### High-Level Description

Minute-by-minute discrete timeline of reservation capacity and autoscale
telemetry. Serves as the authoritative source for reconciling Edition
Pay-As-You-Go (PAYG) and baseline slot consumption against Cloud Billing
invoices. Retention is 180 days (and one row per minute with changes for older
records).

#### Required IAM Permissions & Predefined Roles

*   Requires `bigquery.reservations.list` on the administration project.
*   **Predefined Roles:** **BigQuery Resource Admin**
    (`roles/bigquery.resourceAdmin`), **BigQuery Resource Editor**
    (`roles/bigquery.resourceEditor`), **BigQuery Resource Viewer**
    (`roles/bigquery.resourceViewer`), **BigQuery User**
    (`roles/bigquery.user`), or **BigQuery Admin** (`roles/bigquery.admin`).

<!-- mdformat off -->
| Column Name | Data Type | Physical Unit | Description & Conversion Formula |
| :--- | :--- | :--- | :--- |
| `autoscale.current_slots` | `INT64` | **Slots** | Active autoscaled slots provisioned during the interval. |
| `autoscale.max_slots` | `INT64` | **Slots** | Maximum configured autoscaler limit ceiling. |
| `edition` | `STRING` | Enum | Target edition tier: `'STANDARD'`, `'ENTERPRISE'`, `'ENTERPRISE_PLUS'`. |
| `ignore_idle_slots` | `BOOLEAN` | Boolean | `FALSE` if slot sharing is enabled across commitments. |
| `is_creation_region` | `BOOLEAN` | Boolean | `TRUE` if current region is the original creation region where baseline reservation slots are billed. `FALSE` in secondary failover regions. |
| `labels` | `ARRAY<RECORD>` | Struct Array | Array of labels associated with the reservation. |
| `max_slots` | `INT64` | **Slots** | Total maximum slot limit for reservation predictability. |
| `period_autoscale_slot_seconds` | `INT64` | **Slot-seconds** | Cumulative dynamic autoscaled compute consumed in that 1-minute slice. **Formula for Billable Autoscale Slot-Hours:** `period_autoscale_slot_seconds / 3600.0`. |
| `period_start` | `TIMESTAMP` | UTC Timestamp | Start time of this 1-minute discrete interval. |
| `per_second_details` | `ARRAY<RECORD>` | Struct Array | Array of 60 per-second capacity and usage snapshots (`start_time`, `autoscale_current_slots`, `autoscale_max_slots`, `slots_assigned`, `slots_max_assigned`, `borrowed_slots`, `lent_slots`). |
| `project_id` | `STRING` | Project ID | ID of the reservation administration project. |
| `project_number` | `INT64` | Numeric ID | Numeric project ID. |
| `reservation_group_path` | `ARRAY<STRING>` | Array | Hierarchical reservation group path. |
| `reservation_id` | `STRING` | Resource Path | Formatted reservation path (`project_id:location.reservation_name`) for joining with `JOBS_TIMELINE`. |
| `reservation_name` | `STRING` | Resource Path | Name of the reservation. |
| `scaling_mode` | `STRING` | Enum | Scaling mode (`'ALL_SLOTS'`, `'IDLE_SLOTS_ONLY'`, `'AUTOSCALE_ONLY'`, `'SCALING_MODE_UNSPECIFIED'`). |
| `scheduling_policy` | `RECORD` | Struct | Default per-project caps within the reservation (`max_slots`, `concurrency`), or `NULL` if unset (Preview / feature-flag gated; verify availability with `SELECT * ... LIMIT 0` before projecting explicitly). |
| `slot_capacity` | `INT64` | **Slots** | Total configured baseline slot capacity. **Formula for Billable Baseline Slots:** `IF(is_creation_region, slot_capacity, 0)`. |
| `slots_assigned` | `INT64` | **Slots** | Instantaneous active baseline allocation. Shifts to secondary region during DR failover events (for invoicing, use `slot_capacity` with `is_creation_region`). |
| `slots_max_assigned` | `INT64` | **Slots** | Maximum slot capacity for reservation including idle sharing (`slots_assigned` if `ignore_idle_slots = TRUE`). |
<!-- mdformat on -->

#### Nested `per_second_details` Schema (Field in `RESERVATIONS_TIMELINE`)

The `per_second_details` column is an `ARRAY<STRUCT>` providing 1-second
discrete capacity and usage snapshots within the 1-minute period:

*   `start_time` (`TIMESTAMP`): The exact UTC timestamp of the second.
*   `autoscale_current_slots` (`INT64`): Autoscaling slots available to the
    reservation at this second (excludes baseline slots). Reflects accurate
    second-by-second scaling when autoscaler adjusts multiple times within a
    minute.
*   `autoscale_max_slots` (`INT64`): Maximum autoscaling slots configured at
    this second (excludes baseline slots).
*   `slots_assigned` (`INT64`): Baseline slot capacity assigned to this
    reservation at this second.
*   `slots_max_assigned` (`INT64`): Maximum slot capacity including idle slot
    sharing (`slots_assigned` if `ignore_idle_slots = TRUE`).
*   `borrowed_slots` (`INT64`): Number of slots consumed from the shared idle
    slot pool. Populated only when `ignore_idle_slots = FALSE` and idle slots
    were used during this second.
*   `lent_slots` (`INT64`): Number of baseline slots borrowed by other
    reservations from this reservation's baseline pool. Populated only when
    `ignore_idle_slots = FALSE` and idle slots were shared during this second.

> [!NOTE] **Array Population Invariant:** When there are autoscale or
> reservation changes during the minute, `per_second_details` is populated with
> 60 elements (one per second). For non-autoscale reservations that remain
> unchanged during that minute, `per_second_details` is an empty array to
> prevent redundant repeating data. To analyze second-level telemetry, use
> `LEFT JOIN UNNEST(per_second_details) AS s`.

### `INFORMATION_SCHEMA.CAPACITY_COMMITMENTS` (and `_BY_PROJECT`)

#### High-Level Description

Lists all currently active dedicated slot commitments, commitment plans, renewal
parameters, and remaining commitment lifecycles.

#### Required IAM Permissions & Predefined Roles

*   Requires `bigquery.capacityCommitments.list` on the administration project.
*   **Predefined Roles:** **BigQuery Resource Admin**
    (`roles/bigquery.resourceAdmin`), **BigQuery Resource Editor**
    (`roles/bigquery.resourceEditor`), **BigQuery Resource Viewer**
    (`roles/bigquery.resourceViewer`), **BigQuery User**
    (`roles/bigquery.user`), or **BigQuery Admin** (`roles/bigquery.admin`).

<!-- mdformat off -->
| Column Name | Data Type | Physical Unit | Description |
| :--- | :--- | :--- | :--- |
| `capacity_commitment_id` | `STRING` | ID String | Unique commitment identifier string. |
| `commitment_plan` | `STRING` | Enum | Commitment duration tier: `'ANNUAL'`, `'THREE_YEAR'`. |
| `ddl` | `STRING` | SQL String | GoogleSQL DDL statement used to create this capacity commitment. |
| `edition` | `STRING` | Enum | Target Edition: `'STANDARD'`, `'ENTERPRISE'`, `'ENTERPRISE_PLUS'`. |
| `is_flat_rate` | `BOOLEAN` | Boolean | `TRUE` for legacy flat-rate commitments; `FALSE` for Edition commitments. |
| `project_id` | `STRING` | Project ID | ID of the administration project. |
| `project_number` | `INT64` | Numeric ID | Number of the administration project. |
| `renewal_plan` | `STRING` | Enum | Plan upon expiry: `'ANNUAL'`, `'THREE_YEAR'`, `'NONE'`. |
| `slot_count` | `INT64` | **Slots** | Dedicated capacity slot quantity. |
| `state` | `STRING` | Enum | Lifecycle state: `'PENDING'`, `'ACTIVE'`. |
<!-- mdformat on -->

### `INFORMATION_SCHEMA.CAPACITY_COMMITMENT_CHANGES_BY_PROJECT` (and `_CHANGES`)

#### High-Level Description

Complete audit log of all commitment purchase, modification, renewal, and
deletion lifecycle events. This view contains current capacity commitments and
deleted capacity commitments (deleted commitments are kept for a maximum of 41
days after which they are removed from the view). Used to construct
running-total historical capacity curves for CUD reconciliation.

#### Required IAM Permissions & Predefined Roles

*   Requires `bigquery.capacityCommitments.list` on the administration project.
*   **Predefined Roles:** **BigQuery Resource Admin**
    (`roles/bigquery.resourceAdmin`), **BigQuery Resource Editor**
    (`roles/bigquery.resourceEditor`), **BigQuery Resource Viewer**
    (`roles/bigquery.resourceViewer`), **BigQuery User**
    (`roles/bigquery.user`), or **BigQuery Admin** (`roles/bigquery.admin`).

<!-- mdformat off -->
| Column Name | Data Type | Physical Unit | Description |
| :--- | :--- | :--- | :--- |
| `action` | `STRING` | Enum | Event action: `'CREATE'`, `'UPDATE'`, `'DELETE'`. Used with `LAG`/`LEAD` to compute point-in-time deltas. |
| `capacity_commitment_id` | `STRING` | ID String | Unique commitment identifier string. |
| `change_timestamp` | `TIMESTAMP` | UTC Timestamp | Timestamp when the commitment lifecycle event occurred. |
| `commitment_end_time` | `TIMESTAMP` | UTC Timestamp | Expiration timestamp when commitment plan expires or renews (`NULL` if not `ACTIVE`). |
| `commitment_plan` | `STRING` | Enum | Duration plan: `'ANNUAL'`, `'THREE_YEAR'`. |
| `commitment_start_time` | `TIMESTAMP` | UTC Timestamp | Timestamp when commitment became active (`NULL` if not `ACTIVE`). |
| `edition` | `STRING` | Enum | Target Edition: `'STANDARD'`, `'ENTERPRISE'`, `'ENTERPRISE_PLUS'`. |
| `failure_status` | `RECORD` | Struct | Failure reason for a `FAILED` commitment plan (`code`, `message`). |
| `is_flat_rate` | `BOOLEAN` | Boolean | `TRUE` for legacy flat-rate commitments; `FALSE` for Edition commitments. |
| `project_id` | `STRING` | Project ID | ID of the administration project. |
| `project_number` | `INT64` | Numeric ID | Number of the administration project. |
| `renewal_plan` | `STRING` | Enum | Plan upon expiry: `'ANNUAL'`, `'THREE_YEAR'`, `'NONE'`. |
| `slot_count` | `INT64` | **Slots** | Dedicated capacity slot quantity. |
| `state` | `STRING` | Enum | Lifecycle state: `'PENDING'`, `'ACTIVE'`, `'DELETED'`. |
| `user_email` | `STRING` | Email | Administrator or identity who initiated change (`'google'` if automated). |
<!-- mdformat on -->

### `INFORMATION_SCHEMA.ASSIGNMENTS` (and `_BY_PROJECT`)

#### High-Level Description

Defines the active mapping of GCP organizations, folders, and projects to
capacity reservations. Controls which compute pool processes query, pipeline,
and ML workloads.

#### Required IAM Permissions & Predefined Roles

*   Requires `bigquery.reservationAssignments.list` on the administration
    project.
*   **Predefined Roles:** **BigQuery Resource Admin**
    (`roles/bigquery.resourceAdmin`), **BigQuery Resource Editor**
    (`roles/bigquery.resourceEditor`), **BigQuery Resource Viewer**
    (`roles/bigquery.resourceViewer`), **BigQuery User**
    (`roles/bigquery.user`), or **BigQuery Admin** (`roles/bigquery.admin`).

<!-- mdformat off -->
| Column Name | Data Type | Physical Unit | Description |
| :--- | :--- | :--- | :--- |
| `assignee_id` | `STRING` | Resource Path | GCP resource path (`projects/123`, `folders/456`, `organizations/789`). |
| `assignee_number` | `INT64` | Numeric ID | Numeric assignee resource ID. |
| `assignee_type` | `STRING` | Enum | Resource level: `'PROJECT'`, `'FOLDER'`, `'ORGANIZATION'`. |
| `assignment_id` | `STRING` | ID String | Unique assignment identifier string. |
| `ddl` | `STRING` | SQL String | GoogleSQL DDL statement used to create this assignment. |
| `job_type` | `STRING` | Enum | Assigned traffic type: `'QUERY'`, `'PIPELINE'`, `'CONTINUOUS'`, `'ML_EXTERNAL'`, `'BACKGROUND'`. |
| `project_id` | `STRING` | Project ID | ID of the administration project. |
| `project_number` | `INT64` | Numeric ID | Number of the administration project. |
| `reservation_name` | `STRING` | Resource Path | Name of the reservation that the assignment uses. |
<!-- mdformat on -->

### `INFORMATION_SCHEMA.ASSIGNMENT_CHANGES_BY_PROJECT` (and `_CHANGES`)

#### High-Level Description

Audit log of all assignment creation, update, and deletion events within the
administration project. This view contains current assignments and deleted
assignments (deleted assignments are kept for a maximum of 41 days after which
they are removed from the view).

#### Required IAM Permissions & Predefined Roles

*   Requires `bigquery.reservationAssignments.list` on the administration
    project.
*   **Predefined Roles:** **BigQuery Resource Admin**
    (`roles/bigquery.resourceAdmin`), **BigQuery Resource Editor**
    (`roles/bigquery.resourceEditor`), **BigQuery Resource Viewer**
    (`roles/bigquery.resourceViewer`), **BigQuery User**
    (`roles/bigquery.user`), or **BigQuery Admin** (`roles/bigquery.admin`).

<!-- mdformat off -->
| Column Name | Data Type | Physical Unit | Description |
| :--- | :--- | :--- | :--- |
| `action` | `STRING` | Enum | Event type: `'CREATE'`, `'UPDATE'`, `'DELETE'`. |
| `assignee_id` | `STRING` | Resource Path | Unique ID of the assignee resource (`projects/123`, `folders/456`, `organizations/789`). |
| `assignee_number` | `INT64` | Numeric ID | Numeric assignee resource ID. |
| `assignee_type` | `STRING` | Enum | Resource type: `'PROJECT'`, `'FOLDER'`, `'ORGANIZATION'`. |
| `assignment_id` | `STRING` | ID String | Unique assignment identifier string. |
| `change_timestamp` | `TIMESTAMP` | UTC Timestamp | Timestamp when the change occurred. |
| `job_type` | `STRING` | Enum | Job type: `'QUERY'`, `'PIPELINE'`. |
| `project_id` | `STRING` | Project ID | ID of the administration project. |
| `project_number` | `INT64` | Numeric ID | Number of the administration project. |
| `reservation_name` | `STRING` | Resource Path | Name of the reservation that the assignment uses. |
| `state` | `STRING` | Enum | State of the assignment: `'PENDING'`, `'ACTIVE'`. |
| `user_email` | `STRING` | Email | Administrator or identity who made the change (`'google'` if automated). |
<!-- mdformat on -->

### `INFORMATION_SCHEMA.BI_CAPACITIES` (and `BI_CAPACITY_CHANGES`)

#### High-Level Description

Defines BI Engine memory capacity allocations and table routing preferences for
sub-second SQL acceleration.

#### Required IAM Permissions & Predefined Roles

*   Requires `bigquery.bireservations.get` on the project.
*   **Predefined Roles:** **BigQuery Resource Admin**
    (`roles/bigquery.resourceAdmin`), **BigQuery Resource Editor**
    (`roles/bigquery.resourceEditor`), **BigQuery Resource Viewer**
    (`roles/bigquery.resourceViewer`), **BigQuery User**
    (`roles/bigquery.user`), or **BigQuery Admin** (`roles/bigquery.admin`).

<!-- mdformat off -->
| Column Name | Data Type | Physical Unit | Description |
| :--- | :--- | :--- | :--- |
| `bi_capacity_name` | `STRING` | String | Name of the capacity object (always `'default'`). |
| `preferred_tables` | `ARRAY<STRING>` | Array | Set of preferred tables this BI Engine capacity must be used for (`NULL` = all queries in project). |
| `project_id` | `STRING` | Project ID | Project containing the BI Engine capacity. |
| `project_number` | `INT64` | Numeric ID | Project number containing the BI Engine capacity. |
| `size` | `INT64` | **Bytes** | BI Engine allocated RAM capacity in bytes. **GiB:** `size / POWER(1024, 3)`. |
| `change_timestamp` | `TIMESTAMP` | UTC Timestamp | (In `BI_CAPACITY_CHANGES`) Timestamp when the update was made. |
| `user_email` | `STRING` | Email | (In `BI_CAPACITY_CHANGES`) Administrator or identity who made the change (`'google'` if automated; `NULL` if unknown). |
<!-- mdformat on -->
schema_others.md 36.4 KB
# BigQuery Platform, Governance & Ingestion INFORMATION_SCHEMA Reference

A comprehensive dictionary, column definition guide, and physical unit
specification for all remaining BigQuery `INFORMATION_SCHEMA` views, covering BI
Engine Acceleration, Security, Streaming Ingestion, Routines, Search/Vector
Indexes, Configurations, and Recommendations.

## Table of Contents

-   [View Scoping & Qualification Matrix](#view-scoping-qualification-matrix)
    (Lines 61-78)
-   [5. Routines, Functions, Stored Procedures & ML Views](#5-routines-functions-stored-procedures-ml-views)
    (Lines 79-178)
    -   [`INFORMATION_SCHEMA.ROUTINES`](#information_schemaroutines) (Lines
        81-119)
    -   [`INFORMATION_SCHEMA.PARAMETERS`](#information_schemaparameters) (Lines
        120-150)
    -   [`INFORMATION_SCHEMA.ROUTINE_OPTIONS`](#information_schemaroutine_options)
        (Lines 151-178)
-   [6. Streaming & Ingestion Views](#6-streaming-ingestion-views) (Lines
    179-248)
    -   [`INFORMATION_SCHEMA.STREAMING_TIMELINE_BY_PROJECT` (and `_BY_ORGANIZATION`, `_BY_FOLDER`)](#information_schemastreaming_timeline_by_project-and-_by_organization-_by_folder)
        (Lines 181-213)
    -   [`INFORMATION_SCHEMA.WRITE_API_TIMELINE_BY_PROJECT` (and `_BY_ORGANIZATION`, `_BY_FOLDER`)](#information_schemawrite_api_timeline_by_project-and-_by_organization-_by_folder)
        (Lines 214-248)
-   [7. Search, Vector, AI Indexes & BI Engine Views](#7-search-vector-ai-indexes-bi-engine-views)
    (Lines 249-407)
    -   [`INFORMATION_SCHEMA.SEARCH_INDEXES` (and `_OPTIONS`)](#information_schemasearch_indexes-and-_options)
        (Lines 251-289)
    -   [`INFORMATION_SCHEMA.SEARCH_INDEX_COLUMNS`](#information_schemasearch_index_columns)
        (Lines 290-315)
    -   [`INFORMATION_SCHEMA.VECTOR_INDEXES` (and `_OPTIONS`)](#information_schemavector_indexes-and-_options)
        (Lines 316-353)
    -   [`INFORMATION_SCHEMA.VECTOR_INDEX_COLUMNS`](#information_schemavector_index_columns)
        (Lines 354-379)
    -   [`INFORMATION_SCHEMA.BI_CAPACITIES` & `BI_CAPACITY_CHANGES`](#information_schemabi_capacities-bi_capacity_changes)
        (Lines 380-407)
-   [8. Security, Access Control, Governance & Policy Views](#8-security-access-control-governance-policy-views)
    (Lines 408-480)
    -   [`INFORMATION_SCHEMA.OBJECT_PRIVILEGES`](#information_schemaobject_privileges)
        (Lines 410-443)
    -   [`INFORMATION_SCHEMA.ROW_ACCESS_POLICIES`](#information_schemarow_access_policies)
        (Lines 444-480)
-   [9. Recommendations & Insights Views](#9-recommendations-insights-views)
    (Lines 481-567)
    -   [`INFORMATION_SCHEMA.RECOMMENDATIONS` (and `_BY_PROJECT`, `_BY_ORGANIZATION`)](#information_schemarecommendations-and-_by_project-_by_organization)
        (Lines 483-525)
    -   [`INFORMATION_SCHEMA.INSIGHTS` (and `_BY_PROJECT`)](#information_schemainsights-and-_by_project)
        (Lines 526-567)
-   [10. Project & Organization Configuration Views](#10-project-organization-configuration-views)
    (Lines 568-680)
    -   [`INFORMATION_SCHEMA.PROJECT_OPTIONS`](#information_schemaproject_options)
        (Lines 570-597)
    -   [`INFORMATION_SCHEMA.EFFECTIVE_PROJECT_OPTIONS`](#information_schemaeffective_project_options)
        (Lines 598-626)
    -   [`INFORMATION_SCHEMA.ORGANIZATION_OPTIONS`](#information_schemaorganization_options)
        (Lines 627-653)
    -   [`INFORMATION_SCHEMA.ORGANIZATION_OPTIONS_CHANGES` (and `PROJECT_OPTIONS_CHANGES`)](#information_schemaorganization_options_changes-and-project_options_changes)
        (Lines 654-680)

## View Scoping & Qualification Matrix

Platform, acceleration, and governance views fall into **Dual-Scoped**,
**Region-Only**, and **Dataset-Only** qualification categories:

<!-- mdformat off -->
| View Family | INFORMATION_SCHEMA View(s) | Qualification Scope | Syntax Pattern & Scoping Rules |
| :--- | :--- | :--- | :--- |
| **BI Engine Acceleration** | `BI_CAPACITIES`, `BI_CAPACITY_CHANGES` | **Region-Only** | `` `{project_id}`.`region-{region}`.INFORMATION_SCHEMA.BI_CAPACITIES``<br>• In-memory RAM capacity and allocation modification logs (`BI_CAPACITY_CHANGES`). |
| **Search Indexes** | `SEARCH_INDEXES`, `SEARCH_INDEX_COLUMNS`, `SEARCH_INDEX_OPTIONS`, `SEARCH_INDEX_COLUMN_OPTIONS`<br><br>`SEARCH_INDEXES_BY_ORGANIZATION` | **Dataset-Only**<br><br><br>**Region-Only** | • Dataset views require `{dataset_id}`.<br>• Org view requires `region-{region}`. |
| **Vector Indexes** | `VECTOR_INDEXES`, `VECTOR_INDEX_COLUMNS`, `VECTOR_INDEX_OPTIONS` | **Dataset-Only** | `` `{project_id}`.`{dataset_id}`.INFORMATION_SCHEMA.{view_name}``<br>• Dataset-qualified vector index metadata, columns, and options. |
| **Access Control** | `OBJECT_PRIVILEGES`<br><br>`ROW_ACCESS_POLICIES` | **Region-Only**<br><br>**Dual-Scoped** | • `OBJECT_PRIVILEGES` requires `region-{region}` and `WHERE object_name = ...`.<br>• `ROW_ACCESS_POLICIES` accepts `region-{region}` or `{dataset_id}`. |
| **Streaming Ingestion** | `STREAMING_TIMELINE*`, `WRITE_API_TIMELINE*` (`_BY_PROJECT`, `_BY_FOLDER`, `_BY_ORGANIZATION`) | **Region-Only** | `` `{project_id}`.`region-{region}`.INFORMATION_SCHEMA.{view_name}``<br>• Streaming buffer and Storage Write API append throughput. |
| **Configurations** | `PROJECT_OPTIONS`, `PROJECT_OPTIONS_CHANGES`, `EFFECTIVE_PROJECT_OPTIONS`, `ORGANIZATION_OPTIONS`, `ORGANIZATION_OPTIONS_CHANGES` | **Region-Only** | `` `{project_id}`.`region-{region}`.INFORMATION_SCHEMA.{view_name}``<br>• Default option settings and audit history. |
| **Insights & Recommendations** | `RECOMMENDATIONS*` (`_BY_PROJECT`, `_BY_ORGANIZATION`), `INSIGHTS*` (`_BY_PROJECT`) | **Region-Only** | `` `{project_id}`.`region-{region}`.INFORMATION_SCHEMA.{view_name}``<br>• Partitioning/clustering, materialized view, and dataset IAM role recommendations. |
| **Routines & Parameters** | `ROUTINES`, `PARAMETERS`, `ROUTINE_OPTIONS` | **Dual-Scoped** | `` `{project_id}`.`region-{region}`.INFORMATION_SCHEMA.{view_name}``<br>OR<br>`` `{project_id}`.`{dataset_id}`.INFORMATION_SCHEMA.{view_name}`` |
<!-- mdformat on -->

## 5. Routines, Functions, Stored Procedures & ML Views

### `INFORMATION_SCHEMA.ROUTINES`

#### High-Level Description

Defines user-defined functions (UDFs), stored procedures, remote functions,
table functions (TVFs), parameter signatures, return types, determinism, and
Cloud Function connection endpoints.

#### Required IAM Permissions & Predefined Roles

*   Requires `bigquery.routines.get` and `bigquery.routines.list` on the target
    dataset or project.
*   **Predefined Roles:** **BigQuery Metadata Viewer**
    (`roles/bigquery.metadataViewer` - Least Privilege), **BigQuery Data
    Viewer** (`roles/bigquery.dataViewer`), or **BigQuery Admin**
    (`roles/bigquery.admin`).

<!-- mdformat off -->
| Column Name | Data Type | Physical Unit | Description |
| :--- | :--- | :--- | :--- |
| `specific_catalog` | `STRING` | Project ID | Project name. |
| `specific_schema` | `STRING` | Dataset ID | Dataset name. |
| `specific_name` | `STRING` | Routine ID | Unique routine identifier. |
| `routine_catalog` | `STRING` | Project ID | Catalog name. |
| `routine_schema` | `STRING` | Dataset ID | Schema name. |
| `routine_name` | `STRING` | Name | Function/procedure name. |
| `routine_type` | `STRING` | Enum | `'FUNCTION'`, `'AGGREGATE FUNCTION'`, `'PROCEDURE'`, `'TABLE FUNCTION'`. |
| `data_type` | `STRING` | SQL Type | Return data type (or `NULL` for procedures). |
| `routine_body` | `STRING` | Enum | `'SQL'` or `'EXTERNAL'` (or `'REMOTE'` for remote functions). |
| `routine_definition` | `STRING` | SQL Code | Routine body expression or JavaScript/Python function text. |
| `external_language` | `STRING` | Enum | `'JAVASCRIPT'` (or `'PYTHON'` for Python UDFs), or `NULL` when defined with SQL or as a remote function. |
| `is_deterministic` | `STRING` | `'YES'` / `'NO'` | Indicates whether identical inputs always return identical results (`NULL` if unknown). |
| `security_type` | `STRING` | Nullable | Security type of the routine (always `NULL`). |
| `created` | `TIMESTAMP` | UTC Timestamp | Creation timestamp. |
| `last_altered` | `TIMESTAMP` | UTC Timestamp | Last modification timestamp. |
| `ddl` | `STRING` | SQL String | DDL statement to recreate the routine. |
| `connection` | `STRING` | Resource Path | Connection name if the routine has one (e.g. Remote Functions or Python UDFs), otherwise `NULL`. |
<!-- mdformat on -->

### `INFORMATION_SCHEMA.PARAMETERS`

#### High-Level Description

Defines parameter signatures, modes, positions, and defaults for BigQuery
routines.

#### Required IAM Permissions & Predefined Roles

*   Requires `bigquery.routines.get` and `bigquery.routines.list` on the target
    dataset or project.
*   **Predefined Roles:** **BigQuery Metadata Viewer**
    (`roles/bigquery.metadataViewer` - Least Privilege), **BigQuery Data
    Viewer** (`roles/bigquery.dataViewer`), or **BigQuery Admin**
    (`roles/bigquery.admin`).

<!-- mdformat off -->
| Column Name | Data Type | Physical Unit | Description |
| :--- | :--- | :--- | :--- |
| `specific_catalog` | `STRING` | Project ID | Project name. |
| `specific_schema` | `STRING` | Dataset ID | Dataset name. |
| `specific_name` | `STRING` | Routine ID | Unique routine identifier. |
| `ordinal_position` | `INT64` | Position | 1-indexed parameter position (0 = return value). |
| `parameter_mode` | `STRING` | Enum | `'IN'`, `'OUT'`, `'INOUT'`. |
| `is_result` | `STRING` | `'YES'` / `'NO'` | `'YES'` if row represents function return value. |
| `parameter_name` | `STRING` | Param Name | Parameter identifier. |
| `data_type` | `STRING` | SQL Type | GoogleSQL data type of parameter. |
| `parameter_default` | `STRING` | SQL Literal | Default value expression. |
| `is_aggregate` | `STRING` | `'YES'` / `'NO'` | Indicates aggregate parameter status. |
<!-- mdformat on -->

### `INFORMATION_SCHEMA.ROUTINE_OPTIONS`

#### High-Level Description

Lists routine-level configuration options defined in `OPTIONS(...)` clauses.

#### Required IAM Permissions & Predefined Roles

*   Requires `bigquery.routines.get` and `bigquery.routines.list` on the target
    dataset or project.
*   **Predefined Roles:** **BigQuery Metadata Viewer**
    (`roles/bigquery.metadataViewer` - Least Privilege), **BigQuery Data
    Viewer** (`roles/bigquery.dataViewer`), or **BigQuery Admin**
    (`roles/bigquery.admin`).

<!-- mdformat off -->
| Column Name | Data Type | Physical Unit | Description |
| :--- | :--- | :--- | :--- |
| `specific_catalog` | `STRING` | Project ID | Project name. |
| `specific_schema` | `STRING` | Dataset ID | Dataset name. |
| `specific_name` | `STRING` | Routine ID | Unique routine identifier. |
| `option_name` | `STRING` | Option Name | Option key. |
| `option_type` | `STRING` | SQL Type | GoogleSQL type of option. |
| `option_value` | `STRING` | Option Value | Configured option value. |
<!-- mdformat on -->

<a id="sec-streaming"></a>

## 6. Streaming & Ingestion Views

### `INFORMATION_SCHEMA.STREAMING_TIMELINE_BY_PROJECT` (and `_BY_ORGANIZATION`, `_BY_FOLDER`)

#### High-Level Description

Provides 1-minute discrete telemetry for real-time data ingestion via BigQuery
Storage Write API and legacy streaming. Tracks ingested payloads, row counts,
and streaming error rates.

#### Required IAM Permissions & Predefined Roles

*   **Project-Level (Least Privilege):** Requires `bigquery.tables.list` on the
    project. Granted by **BigQuery Metadata Viewer**
    (`roles/bigquery.metadataViewer`), **BigQuery Data Viewer**
    (`roles/bigquery.dataViewer`), or **BigQuery Admin**
    (`roles/bigquery.admin`).
*   **`_BY_FOLDER`:** Requires `bigquery.tables.list` on the parent folder.
*   **`_BY_ORGANIZATION`:** Requires `bigquery.tables.list` on the organization.

<!-- mdformat off -->
| Column Name | Data Type | Physical Unit | Description & Conversion Formula |
| :--- | :--- | :--- | :--- |
| `dataset_id` | `STRING` | Dataset ID | Target dataset. |
| `error_code` | `STRING` | Error Code | Ingestion error classification code. |
| `folder_numbers` | `ARRAY<INT64>` | Array | Folder hierarchy IDs containing the project (only in `_BY_FOLDER`). |
| `project_id` | `STRING` | Project ID | Project receiving streamed rows. |
| `project_number` | `INT64` | Numeric ID | Numeric project identifier. |
| `start_timestamp` | `TIMESTAMP` | UTC Timestamp | 1-minute discrete interval timestamp. |
| `table_id` | `STRING` | Table ID | Target table. |
| `total_input_bytes` | `INT64` | **Bytes** | Raw ingested byte payload. |
| `total_requests` | `INT64` | Count | Number of streaming append requests. |
| `total_rows` | `INT64` | Count | Total records ingested. |
<!-- mdformat on -->

### `INFORMATION_SCHEMA.WRITE_API_TIMELINE_BY_PROJECT` (and `_BY_ORGANIZATION`, `_BY_FOLDER`)

#### High-Level Description

Monitors BigQuery Storage Write API traffic, throughput, and committed vs.
default stream modes.

#### Required IAM Permissions & Predefined Roles

*   **Project-Level (Least Privilege):** Requires `bigquery.tables.list` on the
    project. Granted by **BigQuery Metadata Viewer**
    (`roles/bigquery.metadataViewer`), **BigQuery Data Viewer**
    (`roles/bigquery.dataViewer`), or **BigQuery Admin**
    (`roles/bigquery.admin`).
*   **`_BY_FOLDER`:** Requires `bigquery.tables.list` on the parent folder.
*   **`_BY_ORGANIZATION`:** Requires `bigquery.tables.list` on the organization.

<!-- mdformat off -->
| Column Name | Data Type | Physical Unit | Description |
| :--- | :--- | :--- | :--- |
| `dataset_id` | `STRING` | Dataset ID | Target dataset ID. |
| `error_code` | `STRING` | Error Code | Write API error code. |
| `folder_numbers` | `ARRAY<INT64>` | Array | Folder hierarchy IDs containing the project (only in `_BY_FOLDER`). |
| `project_id` | `STRING` | Project ID | Project containing the target tables. |
| `project_number` | `INT64` | Numeric ID | Numeric project identifier. |
| `start_timestamp` | `TIMESTAMP` | UTC Timestamp | 1-minute discrete interval timestamp. |
| `stream_type` | `STRING` | Enum | `'COMMITTED'`, `'PENDING'`, `'BUFFERED'`, `'DEFAULT'`. |
| `table_id` | `STRING` | Table ID | Target table ID. |
| `total_input_bytes` | `INT64` | **Bytes** | Total bytes processed by the Storage Write API. |
| `total_requests` | `INT64` | Count | Number of append requests. |
| `total_rows` | `INT64` | Count | Total rows appended. |
<!-- mdformat on -->

<a id="sec-indexes"></a>

## 7. Search, Vector, AI Indexes & BI Engine Views

### `INFORMATION_SCHEMA.SEARCH_INDEXES` (and `_OPTIONS`)

#### High-Level Description

Monitors BigQuery text Search Indexes, indexing coverage percentages, storage
footprints, text analyzers, and unindexed row backlogs.

#### Required IAM Permissions & Predefined Roles

*   **Dataset/Project Scope (Least Privilege):** Requires `bigquery.tables.get`
    and `bigquery.tables.list` on the dataset or project. Granted by **BigQuery
    Metadata Viewer** (`roles/bigquery.metadataViewer`), **BigQuery Data
    Viewer** (`roles/bigquery.dataViewer`), or **BigQuery Admin**
    (`roles/bigquery.admin`).
*   **`_BY_ORGANIZATION`:** Requires `bigquery.tables.get` and
    `bigquery.tables.list` on the organization.

<!-- mdformat off -->
| Column Name | Data Type | Physical Unit | Description |
| :--- | :--- | :--- | :--- |
| `analyzer` | `STRING` | Enum | Text analyzer: `'LOG_ANALYZER'`, `'NO_OP_ANALYZER'`, `'TEXT_ANALYZER'`. |
| `coverage_percentage` | `INT64` | Percent | Percentage of base table data currently indexed (0–100). |
| `creation_time` | `TIMESTAMP` | UTC Timestamp | Timestamp when index was created. |
| `ddl` | `STRING` | SQL String | DDL statement to recreate search index. |
| `disable_reason` | `STRING` | Reason String | Reason index was disabled. |
| `disable_time` | `TIMESTAMP` | UTC Timestamp | Timestamp when index was disabled. |
| `index_catalog` | `STRING` | Project ID | Project name. |
| `index_name` | `STRING` | Index Name | Search index name. |
| `index_schema` | `STRING` | Dataset ID | Dataset name. |
| `index_status` | `STRING` | Enum | `'ACTIVE'`, `'PENDING DISABLEMENT'`, `'TEMPORARILY DISABLED'`, `'PERMANENTLY DISABLED'`. |
| `last_index_alteration_info` | `RECORD` | Alteration Struct | Details of latest user-triggered index alteration (`status`, `message`, `new_coverage_percentage`, `start_time`, `end_time`, `ddl`). |
| `last_modification_time` | `TIMESTAMP` | UTC Timestamp | Last index modification timestamp. |
| `last_refresh_time` | `TIMESTAMP` | UTC Timestamp | Last completed index build timestamp. |
| `table_name` | `STRING` | Table ID | Base table identifier. |
| `total_logical_bytes` | `INT64` | **Bytes** | Logical storage consumed by search index structures. |
| `total_storage_bytes` | `INT64` | **Bytes** | Physical storage consumed by search index structures. |
| `unindexed_row_count` | `INT64` | Count | Number of base table rows not yet indexed. |
<!-- mdformat on -->

### `INFORMATION_SCHEMA.SEARCH_INDEX_COLUMNS`

#### High-Level Description

Defines columns participating in BigQuery text Search Indexes.

#### Required IAM Permissions & Predefined Roles

*   Requires `bigquery.tables.get` and `bigquery.tables.list` on the dataset or
    project.
*   **Predefined Roles:** **BigQuery Metadata Viewer**
    (`roles/bigquery.metadataViewer` - Least Privilege), **BigQuery Data
    Viewer** (`roles/bigquery.dataViewer`), or **BigQuery Admin**
    (`roles/bigquery.admin`).

<!-- mdformat off -->
| Column Name | Data Type | Physical Unit | Description |
| :--- | :--- | :--- | :--- |
| `index_catalog` | `STRING` | Project ID | Project name. |
| `index_schema` | `STRING` | Dataset ID | Dataset name. |
| `table_name` | `STRING` | Table ID | Table name. |
| `index_name` | `STRING` | Index Name | Search index name. |
| `index_column_name` | `STRING` | Column Name | Name of indexed column. |
| `index_field_path` | `STRING` | Field Path | Field path for struct columns. |
<!-- mdformat on -->

### `INFORMATION_SCHEMA.VECTOR_INDEXES` (and `_OPTIONS`)

#### High-Level Description

Monitors Vector Indexes (e.g. IVF, HNSW, Tree-AH) for vector similarity search
and embedding lookups (`VECTOR_SEARCH`).

#### Required IAM Permissions & Predefined Roles

*   Requires `bigquery.tables.get` and `bigquery.tables.list` on the target
    dataset or project.
*   **Predefined Roles:** **BigQuery Metadata Viewer**
    (`roles/bigquery.metadataViewer` - Least Privilege), **BigQuery Data
    Viewer** (`roles/bigquery.dataViewer`), or **BigQuery Admin**
    (`roles/bigquery.admin`).

<!-- mdformat off -->
| Column Name | Data Type | Physical Unit | Description |
| :--- | :--- | :--- | :--- |
| `coverage_percentage` | `INT64` | Percent | Base table vector data indexing coverage percentage (0–100). |
| `creation_time` | `TIMESTAMP` | UTC Timestamp | Timestamp when vector index was created. |
| `ddl` | `STRING` | SQL String | DDL statement to recreate vector index. |
| `disable_reason` | `STRING` | Reason String | Reason index was disabled. |
| `disable_time` | `TIMESTAMP` | UTC Timestamp | Timestamp when index was disabled. |
| `index_catalog` | `STRING` | Project ID | Project name. |
| `index_name` | `STRING` | Index Name | Vector index name. |
| `index_schema` | `STRING` | Dataset ID | Dataset name. |
| `index_status` | `STRING` | Enum | `'ACTIVE'`, `'PENDING DISABLEMENT'`, `'TEMPORARILY DISABLED'`, `'PERMANENTLY DISABLED'`. |
| `last_index_alteration_info` | `RECORD` | Alteration Struct | Details of latest user-triggered index alteration (`status`, `message`, `new_coverage_percentage`, `start_time`, `end_time`, `ddl`). |
| `last_model_build_time` | `TIMESTAMP` | UTC Timestamp | Timestamp when index model build was initiated. |
| `last_modification_time` | `TIMESTAMP` | UTC Timestamp | Last index modification timestamp. |
| `last_refresh_time` | `TIMESTAMP` | UTC Timestamp | Timestamp when index weights were last updated. |
| `table_name` | `STRING` | Table ID | Base table name. |
| `total_logical_bytes` | `INT64` | **Bytes** | Logical index size. |
| `total_storage_bytes` | `INT64` | **Bytes** | Physical compressed index size. |
| `unindexed_row_count` | `INT64` | Count | Number of vectors pending indexing. |
<!-- mdformat on -->

### `INFORMATION_SCHEMA.VECTOR_INDEX_COLUMNS`

#### High-Level Description

Defines columns participating in BigQuery Vector Indexes.

#### Required IAM Permissions & Predefined Roles

*   Requires `bigquery.tables.get` and `bigquery.tables.list` on the target
    dataset or project.
*   **Predefined Roles:** **BigQuery Metadata Viewer**
    (`roles/bigquery.metadataViewer` - Least Privilege), **BigQuery Data
    Viewer** (`roles/bigquery.dataViewer`), or **BigQuery Admin**
    (`roles/bigquery.admin`).

<!-- mdformat off -->
| Column Name | Data Type | Physical Unit | Description |
| :--- | :--- | :--- | :--- |
| `index_catalog` | `STRING` | Project ID | Project name. |
| `index_column_name` | `STRING` | Column Name | Vector embedding column name. |
| `index_field_path` | `STRING` | Field Path | Field path for struct columns. |
| `index_name` | `STRING` | Index Name | Vector index name. |
| `index_schema` | `STRING` | Dataset ID | Dataset name. |
| `table_name` | `STRING` | Table ID | Table name. |
<!-- mdformat on -->

### `INFORMATION_SCHEMA.BI_CAPACITIES` & `BI_CAPACITY_CHANGES`

#### High-Level Description

Tracks BigQuery BI Engine in-memory acceleration reservations, configured RAM
capacities, and capacity alteration events.

#### Required IAM Permissions & Predefined Roles

*   Requires `bigquery.bireservations.get` on the project.
*   **Predefined Roles:** **BigQuery Resource Admin**
    (`roles/bigquery.resourceAdmin`), **BigQuery Resource Editor**
    (`roles/bigquery.resourceEditor`), **BigQuery Resource Viewer**
    (`roles/bigquery.resourceViewer`), **BigQuery User**
    (`roles/bigquery.user`), or **BigQuery Admin** (`roles/bigquery.admin`).

<!-- mdformat off -->
| Column Name | Data Type | Physical Unit | Description |
| :--- | :--- | :--- | :--- |
| `bi_capacity_name` | `STRING` | String | Name of the capacity object (always `'default'`). |
| `change_timestamp` | `TIMESTAMP` | UTC Timestamp | (In `BI_CAPACITY_CHANGES`) Timestamp when the update was made. |
| `preferred_tables` | `ARRAY<STRING>` | Array | Set of preferred tables this BI Engine capacity must be used for (`NULL` = all queries in project). |
| `project_id` | `STRING` | Project ID | Project hosting the BI Engine capacity. |
| `project_number` | `INT64` | Numeric ID | Project number. |
| `size` | `INT64` | **Bytes** | Configured in-memory RAM capacity allocation. |
| `user_email` | `STRING` | Email | (In `BI_CAPACITY_CHANGES`) Administrator or identity who made the change (`'google'` if automated; `NULL` if unknown). |
<!-- mdformat on -->

## 8. Security, Access Control, Governance & Policy Views

### `INFORMATION_SCHEMA.OBJECT_PRIVILEGES`

#### High-Level Description

Lists explicit IAM role bindings across datasets, tables, views, and external
tables (excludes inherited bindings). Queries **must** include a `WHERE` clause
filtering to a single resource (`WHERE object_name = '{dataset_id}'` for a
dataset, or
`WHERE object_schema = '{dataset_id}' AND object_name = '{table_id}'` for a
table or view).

#### Required IAM Permissions & Predefined Roles

*   Requires `bigquery.datasets.get` on datasets or
    `bigquery.tables.getIamPolicy` on tables and views.
*   **Predefined Roles:** **BigQuery Metadata Viewer**
    (`roles/bigquery.metadataViewer` - Least Privilege), **BigQuery Data
    Viewer** (`roles/bigquery.dataViewer`), **BigQuery Data Editor**
    (`roles/bigquery.dataEditor`), **BigQuery Data Owner**
    (`roles/bigquery.dataOwner`), **BigQuery Security Admin**
    (`roles/bigquery.securityAdmin`), or **BigQuery Admin**
    (`roles/bigquery.admin`).

<!-- mdformat off -->
| Column Name | Data Type | Physical Unit | Description |
| :--- | :--- | :--- | :--- |
| `grantee` | `STRING` | Principal | Grantee identity (`'user:alice@example.com'`, `'group:analysts@example.com'`, `'serviceAccount:app@proj.iam.gserviceaccount.com'`). |
| `object_catalog` | `STRING` | Project ID | Project containing the resource. |
| `object_name` | `STRING` | Resource Name | Name of table, view, or dataset. |
| `object_schema` | `STRING` | Dataset ID | Dataset containing the resource (`NULL` if the resource itself is a dataset). |
| `object_type` | `STRING` | Enum | `'SCHEMA'`, `'TABLE'`, `'VIEW'`, `'EXTERNAL'`. |
| `privilege_type` | `STRING` | Role ID | IAM Role ID granted (e.g. `'roles/bigquery.dataViewer'`). |
<!-- mdformat on -->

### `INFORMATION_SCHEMA.ROW_ACCESS_POLICIES`

#### High-Level Description

Lists active row-level access policies and their SQL `filter_predicate`
expressions across tables in a dataset (`{dataset_id}`) or across a project in a
region (`region-{region}`). This view omits policy grantees and `ddl`, and
returns zero rows without error for hidden, BigLake, or Analytics Hub linked
datasets (for linked datasets, inspect the publisher source dataset instead). To
inspect policy grantees, use
`bq ls --row_access_policies {dataset_id}.{table_id}` (which calls
`rowAccessPolicies.getIamPolicy` for each listed policy) or call the
`rowAccessPolicies.getIamPolicy` REST API method after listing policy IDs via
`INFORMATION_SCHEMA.ROW_ACCESS_POLICIES` or `rowAccessPolicies.list` (requires
`bigquery.rowAccessPolicies.getIamPolicy` for grantees).

#### Required IAM Permissions & Predefined Roles

*   Requires `bigquery.rowAccessPolicies.get` and
    `bigquery.rowAccessPolicies.list` on the dataset (for dataset-qualified
    queries) or project (for region-qualified queries).
*   **Predefined Roles:** **BigQuery Data Owner** (`roles/bigquery.dataOwner`),
    **BigQuery Security Admin** (`roles/bigquery.securityAdmin`), or **BigQuery
    Admin** (`roles/bigquery.admin`).

<!-- mdformat off -->
| Column Name | Data Type | Physical Unit | Description |
| :--- | :--- | :--- | :--- |
| `table_catalog` | `STRING` | Project ID | ID of the project containing the row access policy. |
| `table_schema` | `STRING` | Dataset ID | Name of the dataset containing the row access policy. |
| `table_name` | `STRING` | Table Name | Name of the table containing the row access policy. |
| `row_access_policy_name` | `STRING` | Policy Name | Name of the row access policy. |
| `filter_predicate` | `STRING` | SQL Expression | Boolean SQL expression defining which rows are accessible by the policy. |
| `creation_time` | `TIMESTAMP` | UTC Timestamp | Timestamp when the row access policy was created. |
| `last_modified_time` | `TIMESTAMP` | UTC Timestamp | Timestamp when the row access policy was last modified. |
<!-- mdformat on -->

## 9. Recommendations & Insights Views

### `INFORMATION_SCHEMA.RECOMMENDATIONS` (and `_BY_PROJECT`, `_BY_ORGANIZATION`)

#### High-Level Description

Surfaces automated BigQuery Recommender recommendations for cost savings,
performance optimization, partition/cluster suggestions, materialized views, and
dataset IAM role recommendations.

#### Required IAM Permissions & Predefined Roles

*   **Project-Level (Least Privilege):** Returns recommendations for each
    supported recommender whose `.get` and `.list` permissions the caller holds
    (`recommender.bigqueryPartitionClusterRecommendations.get`/`list`,
    `recommender.bigqueryMaterializedViewRecommendations.get`/`list`, and
    `recommender.iamPolicyRecommendations.get`/`list`), granted by **Recommender
    Viewer** (`roles/recommender.viewer`), **BigQuery Partitioning Clustering
    Recommender Viewer** (`roles/recommender.bigqueryPartitionClusterViewer`),
    **BigQuery Materialized View Recommender Viewer**
    (`roles/recommender.bigqueryMaterializedViewViewer`), or **IAM Recommender
    Viewer** (`roles/recommender.iamViewer`). Dataset IAM role recommendations
    also check `iam.roles.get`/`list` on the project and
    `bigquery.datasets.getIamPolicy` on the dataset.
*   **`_BY_ORGANIZATION`:** Requires the corresponding recommender permissions
    at the organization level.

<!-- mdformat off -->
| Column Name | Data Type | Physical Unit | Description |
| :--- | :--- | :--- | :--- |
| `additional_details` | `RECORD` | Struct | JSON details and recommended DDL/CLI operations (`operations.action`, `operations.path`, `operations.value`). |
| `associated_insight_ids` | `ARRAY<STRING>` | IDs | IDs of `INSIGHTS` supporting this recommendation. |
| `description` | `STRING` | Text | Human-readable recommendation text and rationale. |
| `last_updated_time` | `TIMESTAMP` | UTC Timestamp | Timestamp when recommendation was generated or refreshed. |
| `primary_impact` | `RECORD` | Struct | Cost, performance, or security impact (`category`, `cost_projection.duration_seconds`). |
| `priority` | `STRING` | Enum | `'P1'`, `'P2'`, `'P3'`, `'P4'`. |
| `project_id` | `STRING` | Project ID | Project ID. |
| `project_number` | `STRING` | Numeric ID | Project number. |
| `recommendation_id` | `STRING` | Base64 ID | Unique recommendation identifier. |
| `recommender` | `STRING` | String | Recommender type (e.g. `'google.bigquery.table.PartitionClusterRecommender'`). |
| `state` | `STRING` | Enum | `'ACTIVE'`, `'CLAIMED'`, `'SUCCEEDED'`, `'DISMISSED'`. |
| `subtype` | `STRING` | String | Subtype classification (e.g. `'PARTITION'`, `'CLUSTER'`). |
| `target_resources` | `ARRAY<STRING>` | Resource Paths | Fully qualified GCP resources affected by recommendation. |
<!-- mdformat on -->

### `INFORMATION_SCHEMA.INSIGHTS` (and `_BY_PROJECT`)

#### High-Level Description

Surfaces underlying workload signals, dataset IAM permission usage, table scan
patterns, and stats that trigger recommender actions.

#### Required IAM Permissions & Predefined Roles

*   **Project-Level (Least Privilege):** Returns insights for each supported
    recommender whose insight `.get` and `.list` permissions the caller holds
    (`recommender.bigqueryTableStatsInsights.get`/`list`,
    `recommender.bigqueryMaterializedViewInsights.get`/`list`, and
    `recommender.iamPolicyInsights.get`/`list`), granted by **Recommender
    Viewer** (`roles/recommender.viewer`), **BigQuery Partitioning Clustering
    Recommender Viewer** (`roles/recommender.bigqueryPartitionClusterViewer`),
    **BigQuery Materialized View Recommender Viewer**
    (`roles/recommender.bigqueryMaterializedViewViewer`), or **IAM Recommender
    Viewer** (`roles/recommender.iamViewer`). Dataset IAM insights also check
    `iam.roles.get`/`list` on the project and `bigquery.datasets.getIamPolicy`
    on the dataset.

<!-- mdformat off -->
| Column Name | Data Type | Physical Unit | Description |
| :--- | :--- | :--- | :--- |
| `additional_details` | `RECORD` | Struct | JSON details and observation period (`observation_period_seconds`). |
| `associated_recommendation_ids` | `ARRAY<STRING>` | IDs | Full recommendation names/IDs associated with this insight. |
| `category` | `STRING` | Enum | `'COST'`, `'PERFORMANCE'`, `'SECURITY'`. |
| `description` | `STRING` | Text | Description of observed performance signal. |
| `insight_id` | `STRING` | Base64 ID | Unique insight identifier. |
| `insight_type` | `STRING` | String | Insight type (e.g. `'google.bigquery.table.StatsInsight'`). |
| `last_updated_time` | `TIMESTAMP` | UTC Timestamp | Generation timestamp. |
| `project_id` | `STRING` | Project ID | Project ID. |
| `project_number` | `STRING` | Numeric ID | Project number. |
| `severity` | `STRING` | Enum | `'LOW'`, `'MEDIUM'`, `'HIGH'`, `'CRITICAL'`. |
| `state` | `STRING` | Enum | `'ACTIVE'`, `'ACCEPTED'`, `'DISMISSED'`. |
| `subtype` | `STRING` | String | Subtype classification (`'TABLE_STATS'`). |
| `target_resources` | `ARRAY<STRING>` | Resource Paths | Targeted GCP resources. |
<!-- mdformat on -->

<a id="sec-config"></a>

## 10. Project & Organization Configuration Views

### `INFORMATION_SCHEMA.PROJECT_OPTIONS`

#### High-Level Description

Lists configured project-level default options (e.g. default time travel
duration, KMS keys, default query priority, and default reservation
assignments).

#### Required IAM Permissions & Predefined Roles

*   Requires `bigquery.config.get` on the project.
*   **Predefined Roles:** **BigQuery Job User** (`roles/bigquery.jobUser` -
    Least Privilege), **BigQuery User** (`roles/bigquery.user`), **BigQuery Data
    Editor** (`roles/bigquery.dataEditor`), **BigQuery Data Owner**
    (`roles/bigquery.dataOwner`), or **BigQuery Admin**
    (`roles/bigquery.admin`).

<!-- mdformat off -->
| Column Name | Data Type | Physical Unit | Description |
| :--- | :--- | :--- | :--- |
| `project_number` | `INT64` | Numeric ID | Project number. |
| `project_id` | `STRING` | Project ID | Project identifier. |
| `option_name` | `STRING` | Option Name | Option identifier (e.g. `'default_time_zone'`, `'default_kms_key_name'`, `'default_query_job_timeout_ms'`). |
| `option_description` | `STRING` | Text | Description of the option's behavior. |
| `option_type` | `STRING` | SQL Type | GoogleSQL data type. |
| `option_value` | `STRING` | Value String | Configured parameter value. |
<!-- mdformat on -->

### `INFORMATION_SCHEMA.EFFECTIVE_PROJECT_OPTIONS`

#### High-Level Description

Lists effective project options accounting for organization, folder, and project
inheritance hierarchy.

#### Required IAM Permissions & Predefined Roles

*   Requires `bigquery.config.get` on the project.
*   **Predefined Roles:** **BigQuery Job User** (`roles/bigquery.jobUser` -
    Least Privilege), **BigQuery User** (`roles/bigquery.user`), **BigQuery Data
    Editor** (`roles/bigquery.dataEditor`), **BigQuery Data Owner**
    (`roles/bigquery.dataOwner`), or **BigQuery Admin**
    (`roles/bigquery.admin`).

<!-- mdformat off -->
| Column Name | Data Type | Physical Unit | Description |
| :--- | :--- | :--- | :--- |
| `project_number` | `INT64` | Numeric ID | Project number. |
| `project_id` | `STRING` | Project ID | Project identifier. |
| `option_name` | `STRING` | Option Name | Option identifier. |
| `option_description` | `STRING` | Text | Description of the option's behavior. |
| `option_type` | `STRING` | SQL Type | GoogleSQL data type of `option_value`. |
| `option_value` | `STRING` | Value String | Effective option value. |
| `option_set_level` | `STRING` | Enum | Hierarchy level where the setting is defined (`'projects'`, `'folders'`, `'organizations'`; unset options are omitted). |
| `option_set_on_id` | `STRING` | Resource ID | Project ID for `'projects'`, slash-separated folder numbers (`parent/.../child`) for `'folders'`, or `""` for `'organizations'`. |
<!-- mdformat on -->

### `INFORMATION_SCHEMA.ORGANIZATION_OPTIONS`

#### High-Level Description

Defines organization-level default configuration settings across BigQuery
projects.

#### Required IAM Permissions & Predefined Roles

*   Requires `bigquery.config.get` on the target project (defaults to the
    query-execution project when `{project_id}` is omitted; also satisfied via
    organization/folder IAM inheritance).
*   **Predefined Roles:** **BigQuery Job User** (`roles/bigquery.jobUser` -
    Least Privilege), **BigQuery User** (`roles/bigquery.user`), **BigQuery Data
    Editor** (`roles/bigquery.dataEditor`), **BigQuery Data Owner**
    (`roles/bigquery.dataOwner`), or **BigQuery Admin**
    (`roles/bigquery.admin`).

<!-- mdformat off -->
| Column Name | Data Type | Physical Unit | Description |
| :--- | :--- | :--- | :--- |
| `option_name` | `STRING` | Option Name | Organization setting name. |
| `option_description` | `STRING` | Text | Option description. |
| `option_type` | `STRING` | SQL Type | Option data type. |
| `option_value` | `STRING` | Value String | Configured organization-wide value. |
<!-- mdformat on -->

### `INFORMATION_SCHEMA.ORGANIZATION_OPTIONS_CHANGES` (and `PROJECT_OPTIONS_CHANGES`)

#### High-Level Description

Maintains an audit log of organization-level and project-level configuration
changes (`PROJECT_OPTIONS_CHANGES` scopes to a single project).

#### Required IAM Permissions & Predefined Roles

*   Requires `bigquery.config.update` on the **organization** (for
    `ORGANIZATION_OPTIONS_CHANGES`, enforced at the organization level) or on
    the **target project** (for `PROJECT_OPTIONS_CHANGES`; defaults to the
    query-execution project when `{project_id}` is omitted, or inherited from
    folder/organization).
*   **Predefined Roles:** **BigQuery Admin** (`roles/bigquery.admin`) on the
    organization (for `ORGANIZATION_OPTIONS_CHANGES`) or target project (for
    `PROJECT_OPTIONS_CHANGES`).

<!-- mdformat off -->
| Column Name | Data Type | Physical Unit | Description |
| :--- | :--- | :--- | :--- |
| `project_id` | `STRING` | Project ID | Project ID (`NULL` for organization-level changes). |
| `project_number` | `INT64` | Numeric ID | Project number (`NULL` for organization-level changes). |
| `update_time` | `TIMESTAMP` | UTC Timestamp | Timestamp of option change. |
| `username` | `STRING` | User Identity | Email or federated identity of administrator who committed the change. |
| `updated_options` | `JSON` | JSON Struct | JSON object containing previous and new setting values. |
<!-- mdformat on -->
schema_storage.md 36.4 KB
# BigQuery Storage & Catalog INFORMATION_SCHEMA Reference

A comprehensive dictionary, column definition guide, and physical unit
specification for all Storage, Table, Column, Partition, Snapshot, and Dataset
views in BigQuery `INFORMATION_SCHEMA`.

## Table of Contents

-   [View Scoping & Qualification Matrix](#view-scoping-qualification-matrix)
    (Lines 46-61)
-   [3. Storage Footprint, Partitions & Table Metadata Views](#3-storage-footprint-partitions-table-metadata-views)
    (Lines 62-443)
    -   [`INFORMATION_SCHEMA.TABLE_STORAGE_USAGE_TIMELINE` (and `_BY_PROJECT`, `_BY_ORGANIZATION`, `_BY_FOLDER`)](#information_schematable_storage_usage_timeline-and-_by_project-_by_organization-_by_folder)
        (Lines 64-115)
    -   [`INFORMATION_SCHEMA.TABLE_STORAGE` (and `_BY_PROJECT`, `_BY_ORGANIZATION`, `_BY_FOLDER`)](#information_schematable_storage-and-_by_project-_by_organization-_by_folder)
        (Lines 116-171)
    -   [`INFORMATION_SCHEMA.TABLES`](#information_schematables) (Lines 172-218)
    -   [`INFORMATION_SCHEMA.TABLE_OPTIONS`](#information_schematable_options)
        (Lines 219-246)
    -   [`INFORMATION_SCHEMA.TABLE_SNAPSHOTS`](#information_schematable_snapshots)
        (Lines 247-277)
    -   [`INFORMATION_SCHEMA.PARTITIONS`](#information_schemapartitions) (Lines
        278-309)
    -   [`INFORMATION_SCHEMA.COLUMNS`](#information_schemacolumns) (Lines
        310-354)
    -   [`INFORMATION_SCHEMA.COLUMN_FIELD_PATHS`](#information_schemacolumn_field_paths)
        (Lines 355-387)
    -   [`INFORMATION_SCHEMA.VIEWS`](#information_schemaviews) (Lines 388-414)
    -   [`INFORMATION_SCHEMA.MATERIALIZED_VIEWS`](#information_schemamaterialized_views)
        (Lines 415-443)
-   [4. Datasets, Replication & Sharing Views](#4-datasets-replication-sharing-views)
    (Lines 444-629)
    -   [`INFORMATION_SCHEMA.SCHEMATA`](#information_schemaschemata) (Lines
        446-475)
    -   [`INFORMATION_SCHEMA.SCHEMATA_OPTIONS`](#information_schemaschemata_options)
        (Lines 476-501)
    -   [`INFORMATION_SCHEMA.SCHEMATA_REPLICAS` (and `_BY_FAILOVER_RESERVATION`)](#information_schemaschemata_replicas-and-_by_failover_reservation)
        (Lines 502-536)
    -   [`INFORMATION_SCHEMA.SCHEMATA_LINKS` & `SHARED_DATASET_USAGE`](#information_schemaschemata_links-shared_dataset_usage)
        (Lines 537-571)
    -   [`INFORMATION_SCHEMA.TABLE_CONSTRAINTS`](#information_schematable_constraints)
        (Lines 572-601)
    -   [`INFORMATION_SCHEMA.KEY_COLUMN_USAGE`](#information_schemakey_column_usage)
        (Lines 602-629)

## View Scoping & Qualification Matrix

Storage, table, and dataset views fall into **Dual-Scoped**, **Region-Only**,
and **Dataset-Only** qualification categories:

<!-- mdformat off -->
| View Family | INFORMATION_SCHEMA View(s) | Qualification Scope | Syntax Pattern & Scoping Rules |
| :--- | :--- | :--- | :--- |
| **Storage Footprints** | `TABLE_STORAGE*` (`_BY_PROJECT`, `_BY_FOLDER`, `_BY_ORGANIZATION`), `TABLE_STORAGE_USAGE_TIMELINE*` | **Region-Only** | `` `{project_id}`.`region-{region}`.INFORMATION_SCHEMA.TABLE_STORAGE*``<br>• Storage billing models (Logical vs Physical) and daily usage integrals (`MiB * seconds`). |
| **Tables & Metadata** | `TABLES`, `TABLE_OPTIONS`, `COLUMNS`, `COLUMN_FIELD_PATHS`, `VIEWS`, `MATERIALIZED_VIEWS` | **Dual-Scoped** | `` `{project_id}`.`region-{region}`.INFORMATION_SCHEMA.{view_name}``<br>OR<br>`` `{project_id}`.`{dataset_id}`.INFORMATION_SCHEMA.{view_name}`` |
| **Table Partitions** | `PARTITIONS` | **Dataset-Only** | `` `{project_id}`.`{dataset_id}`.INFORMATION_SCHEMA.PARTITIONS``<br>• Partition boundaries and storage tiers. Must be qualified with `{dataset_id}`. |
| **Table Snapshots** | `TABLE_SNAPSHOTS` | **Dual-Scoped** | `` `{project_id}`.`region-{region}`.INFORMATION_SCHEMA.TABLE_SNAPSHOTS``<br>OR<br>`` `{project_id}`.`{dataset_id}`.INFORMATION_SCHEMA.TABLE_SNAPSHOTS`` |
| **Datasets & Replication** | `SCHEMATA`, `SCHEMATA_OPTIONS`, `SCHEMATA_REPLICAS*`, `SCHEMATA_LINKS`, `SHARED_DATASET_USAGE` | **Region-Only** | `` `{project_id}`.`region-{region}`.INFORMATION_SCHEMA.{view_name}``<br>• Dataset catalog, cross-region replication, and failover status. |
| **Table Constraints** | `TABLE_CONSTRAINTS`, `KEY_COLUMN_USAGE` | **Dataset-Scoped** | `` `{project_id}`.`{dataset_id}`.INFORMATION_SCHEMA.{view_name}``<br>• Primary/foreign key constraints and participating columns (`{dataset_id}` is documented; `region-{region}` is also accepted at runtime). |
<!-- mdformat on -->

## 3. Storage Footprint, Partitions & Table Metadata Views

### `INFORMATION_SCHEMA.TABLE_STORAGE_USAGE_TIMELINE` (and `_BY_PROJECT`, `_BY_ORGANIZATION`, `_BY_FOLDER`)

#### High-Level Description

Daily historical storage usage time integral. This view is the definitive source
of truth for Cloud Billing invoice storage charges across Active vs. Long-term
and Logical vs. Physical billing tiers.

#### Required IAM Permissions & Predefined Roles

*   **Project-Level (Least Privilege):** Requires `bigquery.tables.get` and
    `bigquery.tables.list` on the project. Granted by **BigQuery Metadata
    Viewer** (`roles/bigquery.metadataViewer`), **BigQuery Data Viewer**
    (`roles/bigquery.dataViewer`), **BigQuery Data Editor**
    (`roles/bigquery.dataEditor`), **BigQuery Data Owner**
    (`roles/bigquery.dataOwner`), or **BigQuery Admin**
    (`roles/bigquery.admin`).
*   **`_BY_FOLDER`:** Requires `bigquery.tables.get` and `bigquery.tables.list`
    on the parent folder.
*   **`_BY_ORGANIZATION`:** Requires `bigquery.tables.get` and
    `bigquery.tables.list` on the organization.

<!-- mdformat off -->
| Column Name | Data Type | Physical Unit | Description |
| :--- | :--- | :--- | :--- |
| `billable_active_logical_usage` | `INT64` | **MiB-seconds** | Active logical usage time integral (<90 days; `0` if dataset uses `PHYSICAL` billing). |
| `billable_active_physical_usage` | `INT64` | **MiB-seconds** | Active physical usage time integral including Time Travel and Fail-Safe (`0` if `LOGICAL` billing). |
| `billable_long_term_logical_usage` | `INT64` | **MiB-seconds** | Long-term logical usage time integral (>90 days; `0` if `PHYSICAL` billing). |
| `billable_long_term_physical_usage` | `INT64` | **MiB-seconds** | Long-term physical usage time integral (>90 days; `0` if `LOGICAL` billing). |
| `billable_total_logical_usage` | `INT64` | **MiB-seconds** | Total logical usage time integral (`0` if `PHYSICAL` billing). |
| `billable_total_physical_usage` | `INT64` | **MiB-seconds** | Total physical usage time integral including Time Travel and Fail-Safe (`0` if `LOGICAL` billing). |
| `folder_numbers` | `ARRAY<INT64>` | Array | Folder hierarchy IDs containing the project (only in `_BY_FOLDER`). |
| `project_id` | `STRING` | Project ID | Project containing the table. |
| `project_number` | `INT64` | Numeric ID | Numeric project ID. |
| `table_catalog` | `STRING` | Project ID | Table catalog / project name. |
| `table_name` | `STRING` | Table ID | Table identifier. |
| `table_schema` | `STRING` | Dataset ID | Dataset containing the table. |
| `usage_date` | `DATE` | **PST Date** | Daily snapshot partition aligned strictly to US Pacific Time (`PST8PDT`). |
<!-- mdformat on -->

> [!CAUTION] **Dimensional Unit Invariant:** `TABLE_STORAGE_USAGE_TIMELINE`
> stores storage continuously integrated over time in **MiB-seconds**. To
> compute daily average billable GiB, always divide by 86,400 (seconds in a day)
> and then by 1,024: `(usage / 86400) / 1024`.

> [!NOTE] **Access Requirements:** Accessing `TABLE_STORAGE_USAGE_TIMELINE`
> requires `bigquery.tables.get` and `bigquery.tables.list` IAM permissions
> (granted by `roles/bigquery.metadataViewer`, `roles/bigquery.dataViewer`,
> `roles/bigquery.dataEditor`, `roles/bigquery.dataOwner`, or
> `roles/bigquery.admin`) on the project. Retention is 90 days (~72-hour lag).
> Does not require `enable_info_schema_storage` opt-in.

### `INFORMATION_SCHEMA.TABLE_STORAGE` (and `_BY_PROJECT`, `_BY_ORGANIZATION`, `_BY_FOLDER`)

#### High-Level Description

Near real-time snapshot of table storage sizes (typically delayed by seconds to
minutes, or up to a day for partition/table expiration changes), including
active vs. long-term uncompressed bytes, compressed physical bytes, Time Travel
retention overhead, and Fail-Safe bytes. Controlled by the
`enable_info_schema_storage` project/organization option (required on
non-grandfathered projects/organizations via `ALTER PROJECT` /
`ALTER ORGANIZATION SET OPTIONS`).

#### Required IAM Permissions & Predefined Roles

*   **Project-Level (Least Privilege):** Requires `bigquery.tables.get` and
    `bigquery.tables.list` on the project. Granted by **BigQuery Metadata
    Viewer** (`roles/bigquery.metadataViewer`), **BigQuery Data Viewer**
    (`roles/bigquery.dataViewer`), **BigQuery Data Editor**
    (`roles/bigquery.dataEditor`), **BigQuery Data Owner**
    (`roles/bigquery.dataOwner`), or **BigQuery Admin**
    (`roles/bigquery.admin`).
*   **`_BY_FOLDER`:** Requires `bigquery.tables.get` and `bigquery.tables.list`
    on the parent folder.
*   **`_BY_ORGANIZATION`:** Requires `bigquery.tables.get` and
    `bigquery.tables.list` on the organization.

<!-- mdformat off -->
| Column Name | Data Type | Physical Unit | Description & Conversion Formula |
| :--- | :--- | :--- | :--- |
| `active_logical_bytes` | `INT64` | **Bytes** | Uncompressed active logical bytes (<90 days unmutated). **GiB:** `active_logical_bytes / POWER(1024, 3)`. |
| `active_physical_bytes` | `INT64` | **Bytes** | Compressed active physical bytes (includes active baseline + time travel). **GiB:** `active_physical_bytes / POWER(1024, 3)`. |
| `creation_time` | `TIMESTAMP` | UTC Timestamp | Table creation timestamp. |
| `current_physical_bytes` | `INT64` | **Bytes** | Baseline physical bytes before Time Travel / Fail-Safe additions. |
| `deleted` | `BOOLEAN` | Boolean | `true` if the table has been deleted and is currently retained in Time Travel or Fail-Safe. |
| `fail_safe_physical_bytes` | `INT64` | **Bytes** | Physical storage consumed by 7-day non-configurable Fail-Safe disaster recovery. Billed at active physical rates under Physical model; free under Logical model. |
| `folder_numbers` | `ARRAY<INT64>` | Array | Folder hierarchy IDs containing the project (only populated in `_BY_FOLDER`). |
| `last_metadata_index_refresh_time` | `TIMESTAMP` | UTC Timestamp | Last metadata indexing refresh timestamp. |
| `long_term_logical_bytes` | `INT64` | **Bytes** | Uncompressed long-term logical bytes (>=90 days unmutated). **GiB:** `long_term_logical_bytes / POWER(1024, 3)`. |
| `long_term_physical_bytes` | `INT64` | **Bytes** | Compressed long-term physical bytes (>=90 days unmutated). **GiB:** `long_term_physical_bytes / POWER(1024, 3)`. |
| `managed_table_type` | `STRING` | Enum | `'NATIVE'` or `'BIGLAKE'` (Preview). |
| `project_id` | `STRING` | Project ID | Project containing table. |
| `project_number` | `INT64` | Numeric ID | Numeric project ID. |
| `storage_last_modified_time` | `TIMESTAMP` | UTC Timestamp | Last storage mutation timestamp. |
| `table_catalog` | `STRING` | Project ID | Table catalog / project name. |
| `table_deletion_reason` | `STRING` | Enum / Reason | Reason for deletion when `deleted` is `TRUE`: `'TABLE_EXPIRATION'`, `'DATASET_DELETION'`, `'USER_DELETED'`. |
| `table_deletion_time` | `TIMESTAMP` | UTC Timestamp | Exact timestamp when the table was deleted. |
| `table_name` | `STRING` | Table ID | Table name. |
| `table_schema` | `STRING` | Dataset ID | Dataset name. |
| `time_travel_physical_bytes` | `INT64` | **Bytes** | Physical storage consumed by Time Travel retention (2 to 7 days). Billed at active physical rates under Physical model; free under Logical model. |
| `total_logical_bytes` | `INT64` | **Bytes** | Sum of `active_logical_bytes` + `long_term_logical_bytes`. |
| `total_partitions` | `INT64` | Count | Number of partitions. |
| `total_physical_bytes` | `INT64` | **Bytes** | Sum of `active_physical_bytes` + `long_term_physical_bytes`. |
| `total_rows` | `INT64` | Count | Current row count. |
| `table_type` | `STRING` | Enum | `'BASE TABLE'`, `'CLONE'`, `'SNAPSHOT'`, `'MATERIALIZED VIEW'`. |
<!-- mdformat on -->

### `INFORMATION_SCHEMA.TABLES`

#### High-Level Description

Lists all tables, views, clones, snapshots, and BigLake tables in the dataset or
project, along with creation times, DDL definitions, and replication statuses.

#### Required IAM Permissions & Predefined Roles

*   Requires `bigquery.tables.get` and `bigquery.tables.list` (and
    `bigquery.routines.get`/`list` for routines) on the target dataset or
    project.
*   **Predefined Roles:** **BigQuery Metadata Viewer**
    (`roles/bigquery.metadataViewer` - Least Privilege), **BigQuery Data
    Viewer** (`roles/bigquery.dataViewer`), **BigQuery Data Editor**
    (`roles/bigquery.dataEditor`), **BigQuery Data Owner**
    (`roles/bigquery.dataOwner`), or **BigQuery Admin**
    (`roles/bigquery.admin`).

<!-- mdformat off -->
| Column Name | Data Type | Physical Unit | Description |
| :--- | :--- | :--- | :--- |
| `base_table_catalog` | `STRING` | Project ID | For table snapshots and clones, the base table project ID. |
| `base_table_name` | `STRING` | Table ID | For table snapshots and clones, the base table name. |
| `base_table_schema` | `STRING` | Dataset ID | For table snapshots and clones, the base table dataset ID. |
| `creation_time` | `TIMESTAMP` | UTC Timestamp | Timestamp when the table was created. |
| `ddl` | `STRING` | SQL String | Complete GoogleSQL DDL statement to reproduce the table. |
| `default_collation_name` | `STRING` | String | Default string collation specification. |
| `is_change_history_enabled` | `STRING` | `'YES'` / `'NO'` | Indicates whether BigQuery change data capture (CDC) history is retained. |
| `is_fine_grained_mutations_enabled` | `STRING` | `'YES'` / `'NO'` | Indicates whether fine-grained mutations are enabled on the table. |
| `is_insertable_into` | `STRING` | `'YES'` / `'NO'` | Indicates whether the table supports DML `INSERT` operations. |
| `is_typed` | `STRING` | `'NO'` | Always `'NO'` for BigQuery tables. |
| `managed_table_type` | `STRING` | Enum | `'NATIVE'` or `'BIGLAKE'` (for BigLake Iceberg tables in BigQuery; Preview). |
| `replica_source_catalog` | `STRING` | Project ID | For materialized view replicas, the base materialized view project ID. |
| `replica_source_name` | `STRING` | Table ID | For materialized view replicas, the base materialized view name. |
| `replica_source_schema` | `STRING` | Dataset ID | For materialized view replicas, the base materialized view dataset ID. |
| `replication_error` | `STRING` | Error String | Error details when `replication_status` indicates a materialized view replica issue. |
| `replication_status` | `STRING` | Enum | Materialized view replica status (`'REPLICATION_STATUS_UNSPECIFIED'`, `'ACTIVE'`, `'SOURCE_DELETED'`, `'PERMISSION_DENIED'`, `'UNSUPPORTED_CONFIGURATION'`). |
| `snapshot_time_ms` | `TIMESTAMP` | UTC Timestamp | For snapshots/clones, the time travel timestamp or creation timestamp on the base table. |
| `sync_status` | `RECORD` | Struct | `STRUCT<last_completion_time TIMESTAMP, error_time TIMESTAMP, error STRUCT<reason STRING, location STRING, message STRING>>` sync status between primary and secondary replicas for cross-region / DR datasets (`NULL` on primary or un-replicated datasets). |
| `table_catalog` | `STRING` | Project ID | Project name. |
| `table_name` | `STRING` | Table ID | Table name. |
| `table_schema` | `STRING` | Dataset ID | Dataset name. |
| `table_type` | `STRING` | Enum | `'BASE TABLE'`, `'VIEW'`, `'MATERIALIZED VIEW'`, `'EXTERNAL'`, `'SNAPSHOT'`, `'CLONE'`. |
| `upsert_stream_apply_watermark` | `TIMESTAMP` | UTC Timestamp | CDC merge watermark timestamp for BigQuery Storage Write API UPSERT streams. |
<!-- mdformat on -->

### `INFORMATION_SCHEMA.TABLE_OPTIONS`

#### High-Level Description

Lists all table-level configuration options specified in the DDL `OPTIONS(...)`
clause, such as partition expiration, KMS encryption keys, and mandatory
partition filter requirements.

#### Required IAM Permissions & Predefined Roles

*   Requires `bigquery.tables.get` and `bigquery.tables.list` on the target
    dataset or project.
*   **Predefined Roles:** **BigQuery Metadata Viewer**
    (`roles/bigquery.metadataViewer` - Least Privilege), **BigQuery Data
    Viewer** (`roles/bigquery.dataViewer`), or **BigQuery Admin**
    (`roles/bigquery.admin`).

<!-- mdformat off -->
| Column Name | Data Type | Key Values | Description |
| :--- | :--- | :--- | :--- |
| `option_name` | `STRING` | `'partition_expiration_days'`, `'require_partition_filter'`, `'kms_key_name'`, `'friendly_name'`, `'description'` | Table configuration parameter. |
| `option_type` | `STRING` | SQL Type | GoogleSQL type of the option. |
| `option_value` | `STRING` | String | Active option value. |
| `table_catalog` | `STRING` | Project ID | Project name. |
| `table_name` | `STRING` | Table ID | Table name. |
| `table_schema` | `STRING` | Dataset ID | Dataset name. |
<!-- mdformat on -->

### `INFORMATION_SCHEMA.TABLE_SNAPSHOTS`

#### High-Level Description

Detailed metadata for BigQuery Table Snapshots, tracking base table lineages and
snapshot creation timestamps.

#### Required IAM Permissions & Predefined Roles

*   Requires `bigquery.tables.get` and `bigquery.tables.list` on the target
    dataset or project (runtime checks both, even though public docs only list
    `bigquery.tables.list`).
*   **Predefined Roles:** **BigQuery Metadata Viewer**
    (`roles/bigquery.metadataViewer` - Least Privilege), **BigQuery Data
    Viewer** (`roles/bigquery.dataViewer`), **BigQuery Data Editor**
    (`roles/bigquery.dataEditor`), **BigQuery Data Owner**
    (`roles/bigquery.dataOwner`), or **BigQuery Admin**
    (`roles/bigquery.admin`).

<!-- mdformat off -->
| Column Name | Data Type | Physical Unit | Description |
| :--- | :--- | :--- | :--- |
| `base_table_catalog` | `STRING` | Project ID | Project ID of the base table. |
| `base_table_name` | `STRING` | Table ID | Base table name. |
| `base_table_schema` | `STRING` | Dataset ID | Dataset ID of the base table. |
| `snapshot_time` | `TIMESTAMP` | UTC Timestamp | Base-table point in time captured by the snapshot (`FOR SYSTEM_TIME AS OF` timestamp if specified, otherwise creation time; see `TABLES.creation_time` for snapshot creation time). |
| `table_catalog` | `STRING` | Project ID | Project containing the snapshot. |
| `table_name` | `STRING` | Table ID | Snapshot table name. |
| `table_schema` | `STRING` | Dataset ID | Dataset containing the snapshot. |
<!-- mdformat on -->

### `INFORMATION_SCHEMA.PARTITIONS`

#### High-Level Description

Provides partition-level metadata for partitioned tables, including row counts,
uncompressed logical bytes, billable bytes, mutation timestamps, and storage
tiers.

#### Required IAM Permissions & Predefined Roles

*   Requires `bigquery.tables.getData` on the table or dataset. *(Note: Unlike
    metadata views, PARTITIONS requires table data access).*
*   **Predefined Roles:** **BigQuery Data Viewer**
    (`roles/bigquery.dataViewer`), **BigQuery Data Editor**
    (`roles/bigquery.dataEditor`), **BigQuery Data Owner**
    (`roles/bigquery.dataOwner`), or **BigQuery Admin**
    (`roles/bigquery.admin`).

<!-- mdformat off -->
| Column Name | Data Type | Physical Unit | Description |
| :--- | :--- | :--- | :--- |
| `last_modified_time` | `TIMESTAMP` | UTC Timestamp | Last write/mutation timestamp. Partitions unmutated for >= 90 days drop to discounted Long-Term rates. |
| `partition_id` | `STRING` | Partition Key | Partition key string (e.g. `'20260815'`, `'__NULL__'`). |
| `storage_tier` | `STRING` | Enum | `'ACTIVE'` (<90 days unmutated) or `'LONG_TERM'` (>= 90 days unmutated). |
| `table_catalog` | `STRING` | Project ID | Project name. |
| `table_name` | `STRING` | Table ID | Table identifier. |
| `table_schema` | `STRING` | Dataset ID | Dataset identifier. |
| `total_billable_bytes` | `INT64` | **Bytes** | Billable bytes for partition. |
| `total_logical_bytes` | `INT64` | **Bytes** | Uncompressed logical size of partition. |
| `total_rows` | `INT64` | Count | Number of rows in partition. |
<!-- mdformat on -->

### `INFORMATION_SCHEMA.COLUMNS`

#### High-Level Description

Defines schema column specifications, GoogleSQL data types, ordinal ordering,
nullability constraints, partitioning columns, clustering positions, policy
tags, and data masking policies.

#### Required IAM Permissions & Predefined Roles

*   Requires `bigquery.tables.get` and `bigquery.tables.list` on the target
    dataset or project.
*   **Predefined Roles:** **BigQuery Metadata Viewer**
    (`roles/bigquery.metadataViewer` - Least Privilege), **BigQuery Data
    Viewer** (`roles/bigquery.dataViewer`), or **BigQuery Admin**
    (`roles/bigquery.admin`).

<!-- mdformat off -->
| Column Name | Data Type | Physical Unit | Description |
| :--- | :--- | :--- | :--- |
| `async_generation_status` | `RECORD` | Status Struct | Populated only while an automatically generated embedding column has an active blocking generation error (`blocking_error.message`; `ErrorProto` struct with `reason`, `location`, `message`, where only `message` is populated); `NULL` for healthy embedding columns (identify those via `is_stored = 'YES'`) and all other columns. |
| `clustering_ordinal_position` | `INT64` | Position | 1-indexed position in the table's clustering key specification. |
| `collation_name` | `STRING` | Collation | Active string collation rule. |
| `column_default` | `STRING` | SQL Literal | Default value expression. |
| `column_name` | `STRING` | Field Name | Top-level column name. |
| `data_governance_tags` | `ARRAY<RECORD>` | Tags Struct Array | IAM and Data Governance tags attached to column. |
| `data_policies` | `ARRAY<RECORD>` | Policy Struct Array | Data policy masking definitions applied to column. |
| `data_type` | `STRING` | SQL Type | GoogleSQL type (`'INT64'`, `'ARRAY<STRING>'`, `'STRUCT<...>'`). |
| `generation_expression` | `STRING` | SQL Expression | GoogleSQL expression used to calculate generated column values. |
| `is_generated` | `STRING` | `'ALWAYS'` / `'NEVER'` | Indicates whether the column is a generated column. |
| `is_hidden` | `STRING` | `'YES'` / `'NO'` | `'YES'` if column is hidden from `SELECT *` expansion. |
| `is_identity` | `STRING` | `'YES'` / `'NO'` | Indicates whether the column is an auto-generated sequence identity. |
| `is_nullable` | `STRING` | `'YES'` / `'NO'` | Nullability constraint. |
| `is_partitioning_column` | `STRING` | `'YES'` / `'NO'` | `'YES'` if this column partitions the table. |
| `is_stored` | `STRING` | `'YES'` / `NULL` | `'YES'` if the column is an automatically generated embedding column; `NULL` otherwise. |
| `is_system_defined` | `STRING` | `'YES'` / `'NO'` | `'YES'` if the column is created and managed automatically by BigQuery. |
| `is_updatable` | `STRING` | Nullable | Always `NULL`. |
| `ordinal_position` | `INT64` | Position | 1-indexed column ordinal position. |
| `policy_tags` | `ARRAY<STRING>` | Resource Paths | Cloud Data Catalog policy tag resource paths for Column-Level Security (CLS). |
| `rounding_mode` | `STRING` | Enum | Rounding mode for `NUMERIC` / `BIGNUMERIC` columns. |
| `table_catalog` | `STRING` | Project ID | Project name. |
| `table_name` | `STRING` | Table ID | Table name. |
| `table_schema` | `STRING` | Dataset ID | Dataset name. |
<!-- mdformat on -->

### `INFORMATION_SCHEMA.COLUMN_FIELD_PATHS`

#### High-Level Description

Defines nested field path specifications for `RECORD` and `STRUCT` columns in
BigQuery tables.

#### Required IAM Permissions & Predefined Roles

*   Requires `bigquery.tables.get` and `bigquery.tables.list` on the target
    dataset or project.
*   **Predefined Roles:** **BigQuery Metadata Viewer**
    (`roles/bigquery.metadataViewer` - Least Privilege), **BigQuery Data
    Viewer** (`roles/bigquery.dataViewer`), or **BigQuery Admin**
    (`roles/bigquery.admin`).

<!-- mdformat off -->
| Column Name | Data Type | Physical Unit | Description |
| :--- | :--- | :--- | :--- |
| `table_catalog` | `STRING` | Project ID | Project name. |
| `table_schema` | `STRING` | Dataset ID | Dataset name. |
| `table_name` | `STRING` | Table ID | Table name. |
| `column_name` | `STRING` | Field Name | Top-level column name. |
| `field_path` | `STRING` | Dot Path | Dot-delimited nested leaf path. |
| `data_type` | `STRING` | SQL Type | GoogleSQL type of the nested field. |
| `description` | `STRING` | Text | Field description. |
| `collation_name` | `STRING` | Collation | Collation rule. |
| `rounding_mode` | `STRING` | Enum | Rounding mode. |
| `policy_tags` | `ARRAY<STRING>` | Resource Paths | Policy tags attached to nested field. |
| `data_governance_tags` | `ARRAY<RECORD>` | Struct Array | Data governance tags. |
| `data_policies` | `ARRAY<RECORD>` | Struct Array | Masking policies applied to field. |
<!-- mdformat on -->

### `INFORMATION_SCHEMA.VIEWS`

#### High-Level Description

Tracks definitions for logical SQL views, including underlying queries, check
options, and SQL dialect flags.

#### Required IAM Permissions & Predefined Roles

*   Requires `bigquery.tables.get` and `bigquery.tables.list` on the target
    dataset or project.
*   **Predefined Roles:** **BigQuery Metadata Viewer**
    (`roles/bigquery.metadataViewer` - Least Privilege), **BigQuery Data
    Viewer** (`roles/bigquery.dataViewer`), or **BigQuery Admin**
    (`roles/bigquery.admin`).

<!-- mdformat off -->
| Column Name | Data Type | Physical Unit | Description |
| :--- | :--- | :--- | :--- |
| `table_catalog` | `STRING` | Project ID | Project name. |
| `table_schema` | `STRING` | Dataset ID | Dataset name. |
| `table_name` | `STRING` | Table ID | View name. |
| `view_definition` | `STRING` | SQL Query | Query expression defining the logical view. |
| `check_option` | `STRING` | String | View check option. |
| `use_standard_sql` | `STRING` | `'YES'` / `'NO'` | `'YES'` for GoogleSQL views. |
<!-- mdformat on -->

### `INFORMATION_SCHEMA.MATERIALIZED_VIEWS`

#### High-Level Description

Monitors Materialized Views, automatic background refresh statuses, and refresh
watermarks.

#### Required IAM Permissions & Predefined Roles

*   Requires `bigquery.tables.get` and `bigquery.tables.list` on the target
    dataset or project.
*   **Predefined Roles:** **BigQuery Metadata Viewer**
    (`roles/bigquery.metadataViewer` - Least Privilege), **BigQuery Data
    Viewer** (`roles/bigquery.dataViewer`), or **BigQuery Admin**
    (`roles/bigquery.admin`).

<!-- mdformat off -->
| Column Name | Data Type | Physical Unit | Description |
| :--- | :--- | :--- | :--- |
| `table_catalog` | `STRING` | Project ID | Project name. |
| `table_schema` | `STRING` | Dataset ID | Dataset name. |
| `table_name` | `STRING` | Table ID | Materialized View name. |
| `last_refresh_time` | `TIMESTAMP` | UTC Timestamp | Last completed Materialized View refresh timestamp. |
| `refresh_watermark` | `TIMESTAMP` | UTC Timestamp | Upstream base table data watermark incorporated into the MV cache. |
| `last_refresh_status` | `RECORD` | Struct | Error details if the last automatic MV refresh failed (`reason`, `message`). |
<!-- mdformat on -->

<a id="sec-datasets"></a>

## 4. Datasets, Replication & Sharing Views

### `INFORMATION_SCHEMA.SCHEMATA`

#### High-Level Description

Defines dataset-level metadata, physical location regions, creation timestamps,
DDL statements, and default collation rules.

#### Required IAM Permissions & Predefined Roles

*   Requires `bigquery.datasets.get` on the target dataset or project.
*   **Predefined Roles:** **BigQuery Metadata Viewer**
    (`roles/bigquery.metadataViewer` - Least Privilege), **BigQuery Data
    Viewer** (`roles/bigquery.dataViewer`), **BigQuery Data Owner**
    (`roles/bigquery.dataOwner`), or **BigQuery Admin**
    (`roles/bigquery.admin`).

<!-- mdformat off -->
| Column Name | Data Type | Key Values | Description |
| :--- | :--- | :--- | :--- |
| `catalog_name` | `STRING` | Project ID | Project name. |
| `schema_name` | `STRING` | Dataset ID | Dataset identifier. |
| `schema_owner` | `STRING` | String | Owning identity. |
| `creation_time` | `TIMESTAMP` | UTC Timestamp | Dataset creation timestamp. |
| `last_modified_time` | `TIMESTAMP` | UTC Timestamp | Last metadata modification timestamp. |
| `location` | `STRING` | Region | Physical geographic storage region (e.g. `'US'`, `'EU'`, `'us-central1'`). |
| `default_collation_name` | `STRING` | Collation | Default collation rule inherited by new tables. |
| `ddl` | `STRING` | SQL String | DDL statement to reproduce the dataset. |
| `sync_status` | `RECORD` | Struct | `STRUCT<last_completion_time TIMESTAMP, error_time TIMESTAMP, error STRUCT<reason STRING, location STRING, message STRING>>` cross-region replication sync health details. |
<!-- mdformat on -->

### `INFORMATION_SCHEMA.SCHEMATA_OPTIONS`

#### High-Level Description

Lists configured dataset options including storage billing models, Time Travel
durations, and default partition expiration days.

#### Required IAM Permissions & Predefined Roles

*   Requires `bigquery.datasets.get` on the target dataset or project.
*   **Predefined Roles:** **BigQuery Metadata Viewer**
    (`roles/bigquery.metadataViewer` - Least Privilege), **BigQuery Data
    Viewer** (`roles/bigquery.dataViewer`), **BigQuery Data Owner**
    (`roles/bigquery.dataOwner`), or **BigQuery Admin**
    (`roles/bigquery.admin`).

<!-- mdformat off -->
| Column Name | Data Type | Key Values | Description |
| :--- | :--- | :--- | :--- |
| `catalog_name` | `STRING` | Project ID | Project name. |
| `schema_name` | `STRING` | Dataset ID | Dataset identifier. |
| `option_name` | `STRING` | `'storage_billing_model'`, `'max_time_travel_hours'`, `'default_table_expiration_days'`, `'default_partition_expiration_days'` | Dataset configuration option. |
| `option_type` | `STRING` | SQL Type | Type of option. |
| `option_value` | `STRING` | `'LOGICAL'`, `'PHYSICAL'`, `'48'`, `'14'` | Configured option value. |
<!-- mdformat on -->

### `INFORMATION_SCHEMA.SCHEMATA_REPLICAS` (and `_BY_FAILOVER_RESERVATION`)

#### High-Level Description

Monitors cross-region dataset replication configurations, secondary replica
health, lag staleness, failover reservations, and backfill progress.

#### Required IAM Permissions & Predefined Roles

*   Requires `bigquery.datasets.get` on the target dataset or project.
*   **Predefined Roles:** **BigQuery Metadata Viewer**
    (`roles/bigquery.metadataViewer` - Least Privilege), **BigQuery Data
    Viewer** (`roles/bigquery.dataViewer`), **BigQuery Data Owner**
    (`roles/bigquery.dataOwner`), or **BigQuery Admin**
    (`roles/bigquery.admin`).

<!-- mdformat off -->
| Column Name | Data Type | Physical Unit | Description |
| :--- | :--- | :--- | :--- |
| `catalog_name` | `STRING` | Project ID | Project name. |
| `creation_complete` | `BOOLEAN` | Boolean | `TRUE` if initial backfill is complete and replica is fully synchronized. |
| `creation_time` | `TIMESTAMP` | UTC Timestamp | Timestamp when replica creation started. |
| `failover_reservation_name` | `STRING` | Reservation ID | Failover reservation name (only in `_BY_FAILOVER_RESERVATION`). |
| `failover_reservation_project_id` | `STRING` | Project ID | Admin project hosting the failover compute reservation (only in `_BY_FAILOVER_RESERVATION`). |
| `location` | `STRING` | Region | Geographic region where replica is hosted. |
| `replica_name` | `STRING` | Replica ID | Unique replica identifier. |
| `replica_primary_assigned` | `BOOLEAN` | Boolean | `TRUE` if this replica has the primary assignment. |
| `replica_primary_assignment_complete` | `BOOLEAN` | Boolean | `TRUE` if primary role assignment has completed. |
| `replica_primary_assignment_completion_time` | `TIMESTAMP` | UTC Timestamp | Timestamp when primary switch to replica was completed. |
| `replica_primary_assignment_time` | `TIMESTAMP` | UTC Timestamp | Timestamp when primary switch to replica was initiated. |
| `replication_time` | `TIMESTAMP` | UTC Timestamp | Replication watermark for the most stale table within the dataset. |
| `schema_name` | `STRING` | Dataset ID | Dataset name. |
| `sync_status` | `RECORD` | Struct | `STRUCT<last_completion_time TIMESTAMP, error_time TIMESTAMP, error STRUCT<reason STRING, location STRING, message STRING>>` sync health details between primary and secondary replicas. |
<!-- mdformat on -->

### `INFORMATION_SCHEMA.SCHEMATA_LINKS` & `SHARED_DATASET_USAGE`

#### High-Level Description

Tracks linked datasets created via Analytics Hub data exchanges, Data Clean
Rooms (DCR), and Cross-Project Shared Dataset usage.

#### Required IAM Permissions & Predefined Roles

*   **`SCHEMATA_LINKS`:** Requires `bigquery.datasets.get` on the project
    (granted by `roles/bigquery.metadataViewer`, `roles/bigquery.dataViewer`,
    `roles/bigquery.dataEditor`, `roles/bigquery.dataOwner`, or
    `roles/bigquery.admin`).
*   **`SHARED_DATASET_USAGE`:** Requires
    `bigquery.datasets.listSharedDatasetUsage` on the source project (granted by
    **BigQuery Data Owner** (`roles/bigquery.dataOwner`) or **BigQuery Admin**
    (`roles/bigquery.admin`); partitioned by `job_start_time` with subscriber
    consumption columns `project_id`, `dataset_id`, `table_id`, `job_id`,
    `linked_project_number`, `subscriber_org_number`, `num_rows_processed`, and
    `total_bytes_processed`).

<!-- mdformat off -->
| Column Name | Data Type | Physical Unit | Description |
| :--- | :--- | :--- | :--- |
| `catalog_name` | `STRING` | Project ID | Source dataset project name. |
| `schema_name` | `STRING` | Dataset ID | Source dataset name. |
| `linked_schema_catalog_name` | `STRING` | Project ID | Subscriber project hosting the linked dataset. |
| `linked_schema_catalog_number` | `INT64` | Numeric ID | Subscriber project number. |
| `linked_schema_name` | `STRING` | Dataset ID | Subscriber linked dataset identifier. |
| `linked_schema_org_display_name` | `STRING` | String | Organization name of the subscriber. |
| `linked_schema_creation_time` | `TIMESTAMP` | UTC Timestamp | Creation timestamp of linked dataset. |
| `shared_asset_id` | `STRING` | Asset ID | Analytics Hub listing or DCR asset identifier. |
| `link_type` | `STRING` | Enum | `'ANALYTICS_HUB'`, `'DATA_CLEAN_ROOM'`. |
<!-- mdformat on -->

### `INFORMATION_SCHEMA.TABLE_CONSTRAINTS`

#### High-Level Description

Defines primary key and foreign key relational constraints on base tables.

#### Required IAM Permissions & Predefined Roles

*   Requires `bigquery.tables.get` (for primary/foreign key definitions) and
    `bigquery.tables.list` on the target dataset or project.
*   **Predefined Roles:** **BigQuery Metadata Viewer**
    (`roles/bigquery.metadataViewer` - Least Privilege), **BigQuery Data
    Viewer** (`roles/bigquery.dataViewer`), or **BigQuery Admin**
    (`roles/bigquery.admin`).

<!-- mdformat off -->
| Column Name | Data Type | Physical Unit | Description |
| :--- | :--- | :--- | :--- |
| `constraint_catalog` | `STRING` | Project ID | Project name. |
| `constraint_schema` | `STRING` | Dataset ID | Dataset name. |
| `constraint_name` | `STRING` | Constraint ID | Unique constraint identifier. |
| `table_catalog` | `STRING` | Project ID | Table project name. |
| `table_schema` | `STRING` | Dataset ID | Table dataset name. |
| `table_name` | `STRING` | Table ID | Table name. |
| `constraint_type` | `STRING` | Enum | `'PRIMARY KEY'` or `'FOREIGN KEY'`. |
| `is_deferrable` | `STRING` | `'NO'` | Indicates deferrability. |
| `initially_deferred` | `STRING` | `'NO'` | Indicates initial deferral status. |
| `enforced` | `STRING` | `'NO'` | `'NO'` for informational GoogleSQL constraints. |
<!-- mdformat on -->

### `INFORMATION_SCHEMA.KEY_COLUMN_USAGE`

#### High-Level Description

Defines column-level participation in primary and foreign key constraints.

#### Required IAM Permissions & Predefined Roles

*   Requires `bigquery.tables.get` and `bigquery.tables.list` on the target
    dataset or project.
*   **Predefined Roles:** **BigQuery Metadata Viewer**
    (`roles/bigquery.metadataViewer` - Least Privilege), **BigQuery Data
    Viewer** (`roles/bigquery.dataViewer`), or **BigQuery Admin**
    (`roles/bigquery.admin`).

<!-- mdformat off -->
| Column Name | Data Type | Physical Unit | Description |
| :--- | :--- | :--- | :--- |
| `constraint_catalog` | `STRING` | Project ID | Project name. |
| `constraint_schema` | `STRING` | Dataset ID | Dataset name. |
| `constraint_name` | `STRING` | Constraint ID | Constraint identifier. |
| `table_catalog` | `STRING` | Project ID | Table project ID. |
| `table_schema` | `STRING` | Dataset ID | Table dataset ID. |
| `table_name` | `STRING` | Table ID | Table name. |
| `column_name` | `STRING` | Column Name | Column participating in constraint. |
| `ordinal_position` | `INT64` | Position | 1-indexed position in composite constraint. |
| `position_in_unique_constraint` | `INT64` | Position | Referenced position in target primary key. |
<!-- mdformat on -->
storage_footprints.md 10.1 KB
# Storage: Logical & Physical Pricing (Bytes Stored)

## Table of Contents

-   [Storage Snapshot & Billing Model Comparison Query](#storage-snapshot-billing-model-comparison-query)
    (Lines 18-107)
-   [Dataset Storage Configuration Query](#dataset-storage-configuration-query)
    (Lines 108-127)
-   [Partition Level Aging & Storage Query](#partition-level-aging-storage-query)
    (Lines 128-146)
-   [Daily Storage Usage Timeline (Time-Integral Conversion)](#daily-storage-usage-timeline-time-integral-conversion)
    (Lines 147-175)
-   [Table Partitioning, Clustering & Filter Enforcement Audit](#table-partitioning-clustering-filter-enforcement-audit)
    (Lines 176-238)
-   [Search Index Coverage Query](#search-index-coverage-query) (Lines 239-262)
-   [Placeholder Definitions](#placeholder-definitions) (Lines 263-268)

## Storage Snapshot & Billing Model Comparison Query

> [!NOTE] The `DECLARE` parameters in the query below reflect default US
> multi-region list pricing ($/GiB/month). Because BigQuery storage pricing
> varies across regions (e.g., non-US regions such as `europe-west1` or
> `asia-northeast1`), verify the current rates for your specific region at
> [BigQuery Storage Pricing](https://cloud.google.com/bigquery/pricing#storage)
> and update the `DECLARE` rates before running.

```googlesql
-- Default pricing parameters below reflect US multi-region standard list rates ($/GiB/month).
-- IMPORTANT: Storage rates vary by region (e.g., non-US regions).
-- Verify and update these DECLARE variables for your specific region before executing.
-- Reference: https://cloud.google.com/bigquery/pricing#storage
DECLARE active_logical_gib_price FLOAT64 DEFAULT 0.02;
DECLARE long_term_logical_gib_price FLOAT64 DEFAULT 0.01;
DECLARE active_physical_gib_price FLOAT64 DEFAULT 0.04;
DECLARE long_term_physical_gib_price FLOAT64 DEFAULT 0.02;

WITH
  storage_sizes AS (
    SELECT
      table_schema AS dataset_name,
      -- Logical
      SUM(IF(deleted = FALSE, active_logical_bytes, 0)) / POWER(1024, 3)
        AS active_logical_gib,
      SUM(IF(deleted = FALSE, long_term_logical_bytes, 0)) / POWER(1024, 3)
        AS long_term_logical_gib,
      -- Physical
      SUM(active_physical_bytes) / POWER(1024, 3) AS active_physical_gib,
      SUM(active_physical_bytes - time_travel_physical_bytes) / POWER(1024, 3)
        AS active_no_tt_physical_gib,
      SUM(long_term_physical_bytes) / POWER(1024, 3)
        AS long_term_physical_gib,
      -- Restorable physical (Time Travel & Fail-Safe)
      SUM(time_travel_physical_bytes) / POWER(1024, 3)
        AS time_travel_physical_gib,
      SUM(fail_safe_physical_bytes) / POWER(1024, 3)
        AS fail_safe_physical_gib
    FROM
      `{project_id}`.`region-{region}`.INFORMATION_SCHEMA.TABLE_STORAGE_BY_PROJECT
    WHERE
      total_physical_bytes + fail_safe_physical_bytes > 0
      AND table_type = 'BASE TABLE'
    GROUP BY
      1
  )
SELECT
  '{region}' AS region,
  dataset_name,
  ROUND(active_logical_gib, 2) AS active_logical_gib,
  ROUND(long_term_logical_gib, 2) AS long_term_logical_gib,
  ROUND(active_physical_gib, 2) AS active_physical_gib,
  ROUND(long_term_physical_gib, 2) AS long_term_physical_gib,
  ROUND(time_travel_physical_gib, 2) AS time_travel_physical_gib,
  ROUND(fail_safe_physical_gib, 2) AS fail_safe_physical_gib,
  -- Compression Ratios
  ROUND(
    SAFE_DIVIDE(active_logical_gib, active_no_tt_physical_gib), 2) AS active_compression_ratio,
  ROUND(
    SAFE_DIVIDE(long_term_logical_gib, long_term_physical_gib), 2) AS long_term_compression_ratio,
  -- Forecast Costs
  ROUND(
    active_logical_gib * active_logical_gib_price, 2) AS forecast_active_logical_cost,
  ROUND(
    long_term_logical_gib * long_term_logical_gib_price, 2) AS forecast_long_term_logical_cost,
  ROUND(
    (active_no_tt_physical_gib + time_travel_physical_gib + fail_safe_physical_gib)
      * active_physical_gib_price,
    2) AS forecast_active_physical_cost,
  ROUND(
    long_term_physical_gib * long_term_physical_gib_price, 2) AS forecast_long_term_physical_cost,
  -- Total Cost Delta (Positive = Physical is cheaper; Negative = Logical is cheaper)
  ROUND(
    (
      (active_logical_gib * active_logical_gib_price)
      + (long_term_logical_gib * long_term_logical_gib_price))
      - (
        (
          active_no_tt_physical_gib
          + time_travel_physical_gib
          + fail_safe_physical_gib)
          * active_physical_gib_price
        + (long_term_physical_gib * long_term_physical_gib_price)),
    2) AS forecast_total_cost_difference
FROM
  storage_sizes
ORDER BY(forecast_active_logical_cost + forecast_active_physical_cost) DESC;
```

## Dataset Storage Configuration Query

Inspect dataset lifecycle parameters (`storage_billing_model`,
`max_time_travel_hours`, `default_partition_expiration_days`):

```googlesql
SELECT
  schema_name AS dataset_name,
  option_name,
  option_value
FROM
  `{project_id}`.`region-{region}`.INFORMATION_SCHEMA.SCHEMATA_OPTIONS
WHERE
  option_name IN (
    'storage_billing_model',
    'max_time_travel_hours',
    'default_partition_expiration_days',
    'default_table_expiration_days');
```

## Partition Level Aging & Storage Query

Inspect partition-level storage and modification timestamps to identify mature
unpartitioned tables or historical partitions:

```googlesql
SELECT
  table_name,
  partition_id,
  last_modified_time,
  ROUND(total_logical_bytes / POWER(1024, 3), 2) AS total_logical_gib
FROM
  `{project_id}`.`{dataset_id}`.INFORMATION_SCHEMA.PARTITIONS
WHERE
  table_name = '{table_name}'
ORDER BY
  partition_id DESC;
```

## Daily Storage Usage Timeline (Time-Integral Conversion)

Convert cumulative `MiB * seconds` storage metrics from
`TABLE_STORAGE_USAGE_TIMELINE` to daily average GiB:

```googlesql
SELECT
  usage_date,
  table_schema AS dataset_name,
  -- Logical average daily GiB: (MiB * seconds / 86400 seconds) / 1024 MiB_per_GiB
  ROUND(SUM(billable_total_logical_usage) / 86400 / 1024, 2) AS avg_daily_logical_gib,
  ROUND(SUM(billable_active_logical_usage) / 86400 / 1024, 2) AS avg_daily_active_logical_gib,
  ROUND(SUM(billable_long_term_logical_usage) / 86400 / 1024, 2) AS avg_daily_long_term_logical_gib,
  -- Physical average daily GiB: (MiB * seconds / 86400 seconds) / 1024 MiB_per_GiB
  ROUND(SUM(billable_total_physical_usage) / 86400 / 1024, 2) AS avg_daily_physical_gib,
  ROUND(SUM(billable_active_physical_usage) / 86400 / 1024, 2) AS avg_daily_active_physical_gib,
  ROUND(SUM(billable_long_term_physical_usage) / 86400 / 1024, 2)
    AS avg_daily_long_term_physical_gib
FROM
  `{project_id}`.`region-{region}`.INFORMATION_SCHEMA.TABLE_STORAGE_USAGE_TIMELINE
WHERE
  usage_date >= DATE_SUB(CURRENT_DATE('PST8PDT'), INTERVAL 7 DAY)
GROUP BY
  1, 2
ORDER BY
  usage_date DESC,
  avg_daily_logical_gib DESC;
```

## Table Partitioning, Clustering & Filter Enforcement Audit

Verify whether referenced tables have `DATE`, `TIMESTAMP`, `DATETIME`, or
`INT64` integer-range partitioning (`is_partitioning_column = 'YES'` and
`data_type`), which high-cardinality filtering and grouping columns are in the
`CLUSTER BY` key (`clustering_ordinal_position`), and whether
`require_partition_filter` is enabled in `INFORMATION_SCHEMA.TABLE_OPTIONS`.
Tables where `partitioning_column IS NULL` are unpartitioned (`DATE` /
`TIMESTAMP` / `DATETIME` indicate time-unit partitioning; `INT64` indicates
integer-range partitioning via `RANGE_BUCKET`), and tables where
`clustering_columns IS NULL` lack clustering on high-cardinality filtering and
grouping columns (`WHERE` and `GROUP BY`). `TABLES`, `COLUMNS`, and
`TABLE_OPTIONS` support dataset (`{dataset_id}`) or regional (`region-{region}`)
scoping.

```googlesql
-- Verify whether referenced tables have DATE, TIMESTAMP, DATETIME, or INT64
-- integer-range partitioning, high-cardinality clustering columns, and
-- require_partition_filter enabled:
SELECT
  c.table_schema AS dataset_id,
  c.table_name,
  MAX(IF(c.is_partitioning_column = 'YES', c.column_name, NULL))
    AS partitioning_column,
  MAX(IF(c.is_partitioning_column = 'YES', c.data_type, NULL))
    AS partitioning_data_type,
  CASE MAX(IF(c.is_partitioning_column = 'YES', c.data_type, NULL))
    WHEN 'DATE' THEN 'DATE partitioning'
    WHEN 'TIMESTAMP' THEN 'TIMESTAMP partitioning'
    WHEN 'DATETIME' THEN 'DATETIME partitioning'
    WHEN 'INT64' THEN 'INT64 integer-range partitioning'
    ELSE 'UNPARTITIONED'
    END AS partitioning_type,
  STRING_AGG(
    IF(c.clustering_ordinal_position IS NOT NULL, c.column_name, NULL),
    ', '
    ORDER BY c.clustering_ordinal_position)
    AS clustering_columns,  -- High-cardinality filtering and grouping columns in CLUSTER BY
  COALESCE(MAX(opt.option_value), 'false') AS require_partition_filter
FROM
  `{project_id}`.`{dataset_id}`.INFORMATION_SCHEMA.COLUMNS AS c
INNER JOIN
  `{project_id}`.`{dataset_id}`.INFORMATION_SCHEMA.TABLES AS t
  ON
    c.table_catalog = t.table_catalog
    AND c.table_schema = t.table_schema
    AND c.table_name = t.table_name
LEFT JOIN
  `{project_id}`.`{dataset_id}`.INFORMATION_SCHEMA.TABLE_OPTIONS AS opt
  ON
    c.table_catalog = opt.table_catalog
    AND c.table_schema = opt.table_schema
    AND c.table_name = opt.table_name
    AND opt.option_name = 'require_partition_filter'
WHERE
  t.table_type = 'BASE TABLE'
GROUP BY
  c.table_schema,
  c.table_name
ORDER BY
  c.table_name;
```

## Search Index Coverage Query

Inspect search index status, coverage, backlog, and storage for a dataset. A
`coverage_percentage` of 0 means the index is not usable in a `SEARCH` query,
even if some data has already been indexed. An index on a base table smaller
than 10 GB is not populated, so its `coverage_percentage` stays 0.

```googlesql
SELECT
  table_name,
  index_name,
  index_status,
  coverage_percentage,
  unindexed_row_count,
  ROUND(total_logical_bytes / POWER(1024, 3), 2) AS index_logical_gib,
  analyzer,
  last_refresh_time,
  ddl
FROM
  `{project_id}`.`{dataset_id}`.INFORMATION_SCHEMA.SEARCH_INDEXES
ORDER BY
  coverage_percentage ASC;
```

## Placeholder Definitions

-   **`{project_id}`**: Google Cloud project ID.
-   **`{region}`**: Storage region (e.g. `us`, `europe-west1`).
-   **`{dataset_id}`**: Dataset name/schema containing the table.
-   **`{table_name}`**: Table name to inspect.

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