bigquery-query-optimization
Skill28 starsChanged 3 months agoApache-2.0View on GitHub
Diagnoses and rewrites slow BigQuery SQL using the query plan (stages, shuffle, workers) — partitioning/clustering pruning, JOIN ordering and broadcast vs. shuffle joins, skewed JOINs, WHERE clause selectivity, and approximate/SQL-vs-JS function choices. Use when a BigQuery query is slow, expensive, or hitting Resources Exceeded, or when reviewing a query plan.
In this repository34 other files it gives its agents.
- build-and-ci-gatesSkill
- cdc-scd-patternsSkill
- code-implementerSkill
- code-smells-expertSkill
- commit-expertSkill
- compliance-verifierSkill
- context-captureSkill
- context-restoreSkill
- database-migration-expertSkill
- design-spec-expertSkill
- documentation-expertSkill
- flutter-architecture-decisionsSkill
- flutter-performance-profilingSkill
- flutter-release-engineeringSkill
- flutter-review-checklistSkill
- flutter-senior-orchestrationSkill
- flutter-test-strategySkill
- flutter-upgrade-migrationSkill
- gcp-data-engineeringSkill
- guidelines-karpathySkill
- loop-engineeringSkill
- performance-scalabilitySkill
- product-analystSkill
- pull-request-expertSkill
- python-expertSkill
- qa-testerSkill
- refactoring-code-expertSkill
- repo-researchSkill
- security-auditSkill
- senior-architect-engineeringSkill
- senior-dev-orchestratorSkill
- sql-query-optimizationSkill
- test-driven-developmentSkill
- testing-expertSkill
The file
We split this skill into the rules it gives an agent
5 rules. About 0 are common, 1 is distinctive, and 4 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈1
Distinctive · estimate
This author's own choices. Worth a look.
4
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 28
High CPU time relative to I/O: Check for expensive JavaScript UDFs, unneeded regex evaluation, or exact COUNT(DISTINCT) on massive …
- Very specific: line 34
JOIN Ordering (BigQuery-Specific): Place the largest table first in the FROM clause, followed by decreasing table sizes (allowing BigQuery …
- Very specific: line 37
Approximate Aggregations: Use APPROX_COUNT_DISTINCT(col) instead of COUNT(DISTINCT col) when ~1% error margin is acceptable.
- Distinctive: line 38
Native SQL UDFs: Avoid JavaScript UDFs (which instantiate V8 subprocesses per call) in favor of native SQL UDFs.
- Very specific: line 63
Claude Code: Run lint_sql_query.py in the workspace shell and execute dry-run estimations with bq.
≈ “Common” is an estimate: at least 1 in 5 of the 213,895 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
BigQuery Query Optimization Skill
Overview
This skill diagnoses and optimizes slow, expensive, or resource-constrained Google Cloud BigQuery SQL queries. It acts as a BigQuery Performance Specialist operating under the core principle: less work → faster query. It focuses on reducing I/O (bytes read), shuffle (data transfer across stages), sorting/grouping overhead, and slot CPU consumption by analyzing execution stages, worker distributions, and pruning mechanics rather than guessing from SQL text alone.
When to Use
Trigger Scenarios
- BigQuery queries that run slowly, consume excessive slot time, or hit
Resources Exceedederrors. - Diagnosing execution stage statistics, shuffle bottlenecks, and data skew across workers.
- Optimizing table scans via partition pruning, clustering alignment, and column selection.
- Statically scanning SQL files and embedded application queries for BigQuery anti-patterns.
When NOT to Use
- Traditional relational databases (PostgreSQL, MySQL, SQL Server): Route to
sql-query-optimization. - High-level GCP lakehouse and storage design: Route to
gcp-data-engineering. - CDC and dimensional SCD Type 2 modeling: Route to
cdc-scd-patterns.
Process
Phase 1: Diagnosing the Execution Plan
Inspect stage-level execution statistics via BigQuery UI or INFORMATION_SCHEMA.JOBS:
- Significant gap between average and max worker compute time: Indicates data skew. Confirm skew with
APPROX_TOP_COUNTon the suspect key and pre-filter or split queries. - High wait/read time in intermediate stages: Indicates excessive data passing through stages. Push filters earlier to reduce shuffle volume.
- High CPU time relative to I/O: Check for expensive JavaScript UDFs, unneeded regex evaluation, or exact
COUNT(DISTINCT)on massive cardinalities.
Phase 2: Query Optimization Rules
- Column Pruning: Replace
SELECT *with explicit columns orSELECT * EXCEPT(...). - Partition & Cluster Pruning: Filter on the partitioned date/timestamp and order
WHERE/JOINconditions to match clustered columns. - Nested & Repeated Fields: Model one-to-many relationships as
ARRAY<STRUCT>instead of flat tables requiring expensiveGROUP BYoperations. - JOIN Ordering (BigQuery-Specific): Place the largest table first in the
FROMclause, followed by decreasing table sizes (allowing BigQuery to broadcast the smaller tables to worker slots). - Filter Before JOINs: Push filters into explicit subqueries before joining; do not rely solely on optimizer pushdown.
- ORDER BY with LIMIT: Unbounded
ORDER BYserializes data onto a single worker node and causesResources Exceeded. Always supply aLIMIT. - Approximate Aggregations: Use
APPROX_COUNT_DISTINCT(col)instead ofCOUNT(DISTINCT col)when ~1% error margin is acceptable. - Native SQL UDFs: Avoid JavaScript UDFs (which instantiate V8 subprocesses per call) in favor of native SQL UDFs.
Phase 3: Automated Static Anti-Pattern Linting
Scan project SQL files or embedded SQL strings in application code (.py, .js, .ts, .java, .go):
python3 ./skills/bigquery-query-optimization/scripts/lint_sql_query.py [optional_path]Usage
Commands & Automation Scripts
# Scan whole repository or specific SQL directory for BigQuery anti-patterns
python3 ./skills/bigquery-query-optimization/scripts/lint_sql_query.py .
python3 ./skills/bigquery-query-optimization/scripts/lint_sql_query.py queries/
# Dry run a rewritten query to verify byte reduction
bq query --use_legacy_sql=false --dry_run < optimized_query.sqlExample Prompts
- "This BigQuery query is throwing 'Resources Exceeded' during a large JOIN — diagnose the query plan and rewrite it."
- "Scan our repository for SQL anti-patterns like SELECT * or ORDER BY without LIMIT."
- "Rewrite this JavaScript UDF as a native BigQuery SQL function to reduce slot time."
Host Execution Instructions
- Claude Code: Run
lint_sql_query.pyin the workspace shell and execute dry-run estimations withbq. - Antigravity: Analyze queries using
lint_sql_query.pyand inspect query execution jobs via GCP tools.
Red Flags
- Putting small tables first in
FROMclauses (violates BigQuery broadcast join optimization). - Executing unbounded
ORDER BYqueries on multi-million row datasets. - Querying partition-enabled tables without a filter on the partition column in
WHERE. - Using
REGEXP_CONTAINSwhen a simpleLIKEwildcard search is sufficient. - Recomputing expensive, repetitive aggregations instead of leveraging Materialized Views.
Verification
- Automated SQL linter reports zero high-severity anti-patterns:
python3 ./skills/bigquery-query-optimization/scripts/lint_sql_query.py . - BigQuery dry-run demonstrates measurable byte reduction compared to original query.
- No unbounded
ORDER BYqueries withoutLIMIT. - Largest table appears first in multi-table
JOINstatements.
References
For before/after SQL query pairs and execution plan blueprints:
- BigQuery Optimization Patterns Reference
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

