1
---
2
name: bigquery-optimization
3
metadata:
4
version: "1.1.2"
5
category: BigDataAndAnalytics
6
publisher: google
7
description: >-
8
Provides workflows to optimize BigQuery environments (capacity planning,
9
editions), storage assets (partitioning, clustering, storage lifecycles,
10
billing models), and SQL queries. Use when optimizing cost, modeling Edition
11
migrations, rightsizing reservations, evaluating logical vs. physical storage,
12
designing table partitioning/clustering, generating table DDL, migrating
13
unpartitioned tables, managing partition expiration, optimizing individual SQL
14
queries, including MERGE statements, or evaluating acceleration structures
15
(search indexes, materialized views, BI Engine).
16
17
Do not use for raw usage reporting (use bigquery-observability), query
18
execution plan analysis, error troubleshooting, or diagnosing why a specific
19
job was slow (use bigquery-troubleshooting).
20
---
21
22
# BigQuery Optimization Workflow
23
24
## Attribution
25
26
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command, you
27
MUST read [Usage Attribution](references/attribution.md). For commands executed
28
directly in the terminal (never in generated scripts, Terraform, or user code),
29
prefix `gcloud` with
30
`CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:bigquery-optimization)"`
31
and append `agent-skills/1.0 (skill:bigquery-optimization)` to `User-Agent` headers.
32
33
## Prerequisites & Environment Setup
34
35
Before executing optimization analyses, evaluating editions, or applying DDL
36
modifications:
37
38
1. **Google Cloud SDK**: Ensure the
39
[Google Cloud SDK](https://cloud.google.com/sdk/docs/install) is installed
40
and configured.
41
2. **Project Selection**: Set the active Google Cloud project:
42
43
```bash
44
gcloud config set project {project_id}
45
```
46
47
3. **API Enablement**: Ensure BigQuery and BigQuery Reservation APIs are
48
enabled:
49
50
```bash
51
gcloud services enable \
52
bigquery.googleapis.com bigqueryreservation.googleapis.com
53
```
54
55
4. **Authentication**: Authenticate the environment:
56
* CLI tools and `bq` commands: `gcloud auth login`
57
* SDKs and automation: `gcloud auth application-default login`
58
* Service accounts: Set
59
`GOOGLE_APPLICATION_CREDENTIALS="/path/to/key.json"`
60
61
5. **Billing & IAM Roles**:
62
* Verify an active Google Cloud Billing account is attached to
63
`{project_id}`.
64
* Ensure appropriate IAM roles:
65
* `roles/bigquery.jobUser`: Running evaluation queries and
66
SQL DDL/DML (pair with read/write roles below to query
67
`INFORMATION_SCHEMA`, `--dry_run` rewrites, or run DDL/DML).
68
* `roles/bigquery.metadataViewer`: Inspecting table, storage,
69
index, and materialized view metadata (`TABLE_STORAGE`,
70
`COLUMNS`, `TABLE_OPTIONS`, `SEARCH_INDEXES`,
71
`MATERIALIZED_VIEWS`).
72
* `roles/bigquery.dataViewer`: Dry-running (`--dry_run`) or
73
evaluating read-only `SELECT` queries against referenced user
74
tables and views (dry-running DML such as `MERGE` also requires
75
`roles/bigquery.dataEditor` on the target table).
76
* `roles/bigquery.resourceViewer` or `roles/bigquery.admin`:
77
Inspecting project-, folder-, or organization-level jobs
78
(`JOBS_BY_PROJECT` for BI Engine and workload analysis) at
79
the matching resource scope, and reservation telemetry on
80
the reservations administration project.
81
* `roles/bigquery.dataEditor` or `roles/bigquery.admin`:
82
Creating or modifying tables, partitioning, clustering,
83
search indexes, and materialized views; dry-running or
84
executing DML (`MERGE`, `UPDATE`) against target tables.
85
* `roles/bigquery.dataOwner` or `roles/bigquery.admin`:
86
Updating dataset-level properties (`storage_billing_model`,
87
dataset Time Travel, and default expiration).
88
* `roles/bigquery.resourceAdmin` or `roles/bigquery.admin`:
89
Managing reservations, capacity commitments, and BI Engine
90
reservations.
91
92
6. **Companion Skills Installation**:
93
This skill is part of a 3-pillar operations suite (`bigquery-observability`,
94
`bigquery-optimization`, `bigquery-troubleshooting`). If any companion skill
95
is not yet installed in your environment, install the full suite:
96
97
```bash
98
npx skills add google/skills --skill bigquery-observability --skill bigquery-optimization --skill bigquery-troubleshooting
99
```
100
101
*(If `bigquery-observability` is not installed, use the self-contained
102
baseline formulas and query templates provided directly in the reference
103
sections below).*
104
105
## Workflows
106
107
Determine the optimization focus of the user's request and follow the relevant
108
workflow:
109
110
- **Telemetry & Observability Baseline:** For direct raw usage telemetry,
111
`INFORMATION_SCHEMA` queries, and baseline metric calculations, consult the
112
[BigQuery observability skill](../bigquery-observability)
113
(`bigquery_observability`). If the `bigquery-observability` companion skill
114
is not available in the active environment, all optimization guidelines, DDL
115
templates, and decision models across this skill and its reference guides
116
are fully self-contained.
117
- **Capacity & Editions Modeling:** Evaluate the cost-efficiency of migrating
118
workloads from On-Demand to Editions, as well as rightsizing active Edition
119
reservations, baseline commitments, and autoscaling caps.
120
* *Instructions:* Read `references/capacity_planning_editions.md` to
121
provide deep links to BigQuery's built-in recommendation UIs (e.g., Slot
122
Estimator) and guide the user through UI navigation: 1. navigate to the
123
Slot Estimator tab, 2. select 'On-Demand' as the source to analyze
124
historical query volume, and 3. review the Cost-Optimized
125
Recommendations and Slot Usage Chart.
126
- **Table & Storage Optimization:** Optimize storage costs from a billing
127
model, physical layout, and lifecycle perspective.
128
* *Billing Architecture:* Read `references/storage_billing_models.md` for
129
guidance on evaluating aggregate compression ratios (e.g. >2:1 threshold
130
in US) to recommend Physical vs. Logical billing, noting that the
131
break-even ratio depends on specific regional rates and custom
132
enterprise contracts. When providing `TABLE_STORAGE` queries, always
133
scope with `WHERE table_schema = '{dataset_id}'`, use the regional
134
dataset view, and warn that 0 rows indicates a region mismatch or lack
135
of native tables rather than zero billable usage.
136
* *Partitioning & Clustering Strategy:* Read
137
`references/table_partitioning_clustering.md` to generate production DDL
138
templates (CREATE TABLE, CTAS migrations for unpartitioned tables, and
139
modifying clustering specifications), enforce pruning with
140
`require_partition_filter = true`, and manage partition limits (up to
141
10,000 partitions/table).
142
* *Lifecycle Management:* Read
143
`references/storage_lifecycle_management.md` to pinpoint inactive data
144
and define precise Time-to-Live (TTL) partition expirations, dataset
145
expirations, and Time Travel window reductions.
146
* *Acceleration Structures:* Read `references/search_indexes.md` to decide
147
when to propose a search index for selective lookups over `STRING` or
148
`JSON` data, write the `CREATE SEARCH INDEX` DDL, and tell the user how
149
to verify index coverage and usage. Read
150
`references/materialized_views.md` to decide when to propose a
151
materialized view for repeated aggregations or joins over large base
152
tables, write the `CREATE MATERIALIZED VIEW` DDL, and tell the user how
153
to verify that smart tuning uses it. Read `references/bi_engine.md` to
154
decide when to propose BI Engine vs. Materialized Views for BI dashboard
155
acceleration, diagnose `PARTIAL` or `DISABLED` BI Engine fallback
156
reasons (`bi_engine_statistics`), and combine BI Engine with
157
materialized views that pre-join or pre-aggregate the data.
158
- **SQL Optimization:** Optimize individual SQL queries, including `MERGE`
159
statements in incremental loads, to reduce slot-time and the amount of data
160
read.
161
* *Instructions:* Follow `references/sql_optimization.md` to recommend how
162
to rewrite the user's SQL query or `MERGE` statement.
163
164
## Execution Guardrails
165
166
- **Terminology & Cost Framing:** Never promise or guarantee "cost-reduction"
167
or "reducing expenditure." Always frame recommendations using the
168
terminology **"optimizing your bill"** or **"improving cost-efficiency."**
169
- **Explicit Scope Framing & Region Resolution:** Always state the target
170
`project_id` and `region` at the very top of your response so the user
171
immediately knows the exact scope being evaluated. Follow this 3-tier
172
resolution hierarchy:
173
1. *Explicit Region:* Use the region specified in the user's prompt (e.g.,
174
`europe-west1`).
175
2. *Contextual Region:* Resolve the region from the specific dataset or
176
resource mentioned in the context.
177
3. *Unspecified Fallback:* Default to `us` / `region-us`, explicitly state
178
that `us` was assumed as the default, and instruct the user to
179
substitute their region if their resources reside elsewhere. *Region
180
Formatting:* In Cloud Console deep links, use the region identifier
181
directly (e.g., `region=us`, `region=europe-west1`). In SQL queries
182
against `INFORMATION_SCHEMA`, use the regional dataset qualifier (e.g.,
183
`region-us`, `region-europe-west1`).
184
- **Zero-Row Result Guard:** If querying `TABLE_STORAGE` with `WHERE
185
table_schema = '{dataset_id}'` returns 0 rows, do not proceed with an empty
186
or zero-usage evaluation. Treat this as an indicator that the dataset may
187
reside in a different region or have no native tables; stop and prompt the
188
user to confirm the dataset's regional location.
189
- **Populate Concrete Parameters:** When generating URLs and SQL queries,
190
always substitute known `project_id` and `region` values directly into the
191
code and links. Never leave literal `{project_id}` or `{location}`
192
placeholders for the user to manually edit.
193
- **No Autonomous Purchasing or Financial Mutations:** Never provide the user
194
with executable scripts (e.g., `gcloud` or `bq` shell commands like `bq
195
update --storage_billing_model=...`) designed to autonomously purchase
196
annual commitments, alter edition tier bindings, or mutate storage billing
197
models. Always guide the user to execute commitment purchases, reservation
198
changes, and storage billing model updates manually via the Cloud Console
199
UI.
200