Skip to main content

Running Analytics Queries with BigQuery

Load data, query it with SQL, and use dry runs, partitioning, and byte limits to control BigQuery costs before a query ever runs.

38 Terms

Overview and What You Will Learn

BigQuery is Google Cloud's serverless data warehouse, and with on-demand pricing you pay for the bytes a query scans, not for rows returned. In this lab you will load data into a partitioned table, run SQL against it, and use dry runs and byte limits to see the cost of a query before you pay for it.

By the end you will be able to:

  • Create a dataset and a partitioned table, and load a CSV file.
  • Run standard SQL queries from the command line.
  • Estimate a query's scan size with --dry_run.
  • Compare SELECT * with a column-specific query on a large public table.
  • Use a required partition filter and a maximum bytes billed cap as guardrails.

Why This Matters in Production

BigQuery makes it easy to run an expensive query by accident. A single SELECT * on a multi-terabyte table, run by a dozen engineers every day just to preview a few rows, can become one of the largest lines on a cloud bill without any incident to point to. Cost control in BigQuery is a set of query habits, and the earlier a team learns them, the smaller the surprise.

Core Principles

BigQuery separates storage from compute. Data is stored by column, and a query reads only the columns it names, so naming fewer columns scans fewer bytes. On a partitioned table, a filter on the partition column lets BigQuery skip whole partitions. Cost follows bytes scanned, not result size or query complexity.

flowchart TD Q[SQL query] -->|Reads| C[Named columns only] C -->|Checks| P{Partition filter?} P -->|Yes| S1[Few partitions scanned] P -->|No| S2[Every partition scanned] S1 -->|Billed| B1([Lower bytes billed]) S2 -->|Billed| B2([Higher bytes billed]) classDef step fill:#326CE5,color:#FFFFFF classDef good fill:#10B981,color:#FFFFFF classDef bad fill:#EF4444,color:#FFFFFF class Q,C,P step class S1,B1 good class S2,B2 bad

Two details help you read cost numbers correctly. A dry run is free and reports the bytes a query would process. On-demand billing also rounds each table read up to a minimum of 10 MB, so tiny tables always look slightly more expensive than their real size.

Detailed Step-by-Step Practical Lab

You need gcloud, the bq tool, and a billing account ID. Cloud Shell has everything.

Step 1: Create a project and enable the API

Bash
export BILLING_ACCOUNT=0X0X0X-0X0X0X-0X0X0X
gcloud projects create gcp-bq-lab-2026 --name="BigQuery Lab"
gcloud billing projects link gcp-bq-lab-2026 --billing-account=$BILLING_ACCOUNT
gcloud config set project gcp-bq-lab-2026
gcloud services enable bigquery.googleapis.com

Step 2: Create a dataset in Mumbai

Bash
bq mk --dataset --location=asia-south1 gcp-bq-lab-2026:sales_data

Step 3: Create a partitioned table that requires a partition filter Partitioning by order_date lets queries skip dates they do not need, and the filter requirement stops accidental full scans.

Bash
bq mk --table \
--time_partitioning_type=DAY \
--time_partitioning_field=order_date \
--require_partition_filter \
gcp-bq-lab-2026:sales_data.orders \
region:STRING,revenue:FLOAT,order_date:DATE

Step 4: Load sample data from a CSV file

Bash
cat > orders.csv << 'CSV_EOF'
region,revenue,order_date
Mumbai,4599.00,2026-01-15
Delhi,2300.50,2026-01-16
Mumbai,1899.00,2026-01-17
Bengaluru,3120.75,2026-01-17
Delhi,980.00,2026-02-02
CSV_EOF
bq load --source_format=CSV --skip_leading_rows=1 \
gcp-bq-lab-2026:sales_data.orders orders.csv

Step 5: Run an aggregate query with a partition filter

Bash
bq query --use_legacy_sql=false \
'SELECT region, SUM(revenue) AS total_revenue
FROM `gcp-bq-lab-2026.sales_data.orders`
WHERE order_date BETWEEN "2026-01-01" AND "2026-01-31"
GROUP BY region
ORDER BY total_revenue DESC'

You should see Mumbai first with 6498.0.

Step 6: See the guardrail reject an unfiltered query

Bash
bq query --use_legacy_sql=false \
'SELECT region, SUM(revenue) FROM `gcp-bq-lab-2026.sales_data.orders` GROUP BY region'

BigQuery refuses it with an error saying you must filter on order_date. That refusal is the point, because the same rule on a large table prevents an expensive mistake.

Step 7: Estimate costs with a dry run on a large public table Your own table is too small to show the effect, so use a public table of about 20 GB. Dry runs do not run the query or cost anything.

Bash
bq query --use_legacy_sql=false --dry_run \
'SELECT * FROM `bigquery-public-data.samples.natality`'
# Only the columns you need
bq query --use_legacy_sql=false --dry_run \
'SELECT year, state, weight_pounds FROM `bigquery-public-data.samples.natality`'

Compare the two "will process N bytes" messages. The second is a small fraction of the first, even though both describe the same table and neither returns a different number of rows.

Tip

Run --dry_run before any query on a table you have not used before. The estimate is free and takes about a second.

Step 8: Put a hard cap on a query's cost --maximum_bytes_billed makes BigQuery fail a query that would bill more than your limit, before any charge happens.

Bash
bq query --use_legacy_sql=false --maximum_bytes_billed=1000000000 \
'SELECT * FROM `bigquery-public-data.samples.natality`'

This fails with an error that the query exceeds the limit for bytes billed, because it would scan far more than 1 GB.

Step 9: Check what a real job was billed

Bash
bq ls -j -n 1
# Copy the job ID from the output, then:
bq show --format=prettyjson -j JOB_ID

Look for totalBytesBilled, which is the number that drives your cost.

Step 10: Clean up

Bash
bq rm -r -f -d gcp-bq-lab-2026:sales_data
rm -f orders.csv
gcloud projects delete gcp-bq-lab-2026 --quiet

Production Best Practices & Common Pitfalls

  • Name columns, never SELECT *. Columns not referenced are not read, so this is the biggest single saving.
  • Partition large tables and require the filter. Partition by a date or timestamp column and set require_partition_filter, so nobody can scan history by mistake.
  • Cluster on frequent filters. Clustering by a column such as customer_id further reduces the data read for filtered queries.
  • Set byte limits. Use maximum_bytes_billed in scheduled queries and applications, and project-level custom quotas for people.
  • Find your expensive queries. This query ranks users by bytes billed over a week. Replace the region with the one your jobs run in:
SQL
SELECT user_email,
ROUND(SUM(total_bytes_billed) / POW(1024, 4), 3) AS tib_billed
FROM `region-us`.INFORMATION_SCHEMA.JOBS_BY_PROJECT
WHERE creation_time > TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 7 DAY)
GROUP BY user_email
ORDER BY tib_billed DESC;
  • Consider capacity pricing for steady workloads. When monthly on-demand spend is large and predictable, slot reservations can cost less and cap spend.
  • Do not use BigQuery as an application database. It is built for analytical scans, not for frequent small reads and writes on every user request. Use Cloud SQL, Spanner, or Firestore for that.
Common Mistake

Believing LIMIT 10 makes a query cheap. On most tables BigQuery still scans every referenced column in full, so you pay for the scan regardless of how few rows are returned.

Common Mistake

Wrapping the partition column in a function, such as WHERE CAST(order_date AS STRING) = "2026-01-15". That can stop partition pruning, so filter on the raw column.

Quick Reference & Troubleshooting Commands

Command Description
bq mk --dataset Create a dataset
bq mk --table --time_partitioning_field Create a partitioned table
bq load Load a file into a table
bq query --use_legacy_sql=false Run a standard SQL query
bq query --dry_run Estimate bytes processed without running
bq query --maximum_bytes_billed= Fail a query that would bill too much
bq show -j JOB_ID Inspect a job, including totalBytesBilled
Symptom Likely fix
Error about a missing partition filter Add a WHERE on the partition column, such as order_date
Query exceeds the limit for bytes billed Select fewer columns, filter partitions, or raise the cap deliberately
Table not found in query Use the full project.dataset.table name, and match the dataset's location
Dry run shows a surprisingly large scan Check for SELECT * and for functions around the partition column

Resources

Artifact Registry

Google Cloud's current, unified package and container image storage service, the successor to the older Container Registry. It supports container images alongside language packages like npm, Maven, and Python packages in one service, and supports cleanup policies to automatically remove old, untagged image versions.

BigQuery

Google Cloud's serverless data warehouse for analytics, priced based on the volume of data a query actually scans rather than pre-provisioned compute capacity. Selecting only needed columns and querying a properly partitioned table's relevant date range are the two highest-impact levers for controlling BigQuery cost.

Bigtable (GCP)

A wide-column NoSQL database built for very high throughput at extremely low latency, suited to time-series data, IoT telemetry, and analytics workloads with massive write volume. It is a specialized tool distinct from Firestore's document model or Cloud SQL's relational model.

Billing Account (GCP)

A separate object from a Project that holds the actual payment method for Google Cloud usage. One Billing Account can be linked to many Projects, all of whose usage is billed to that same account, letting a company centralize payment while individual Projects retain their own separate IAM control over resources.

Cloud Armor

A security policy service attached to a Global External HTTP(S) Load Balancer, filtering malicious requests before they reach the backend. It supports rate-based rules blocking a single source IP exceeding a request threshold, and preconfigured WAF rules blocking common attack patterns like SQL injection, Google's equivalent of AWS WAF or Azure WAF.

Cloud Functions (GCP)

Google Cloud's event-driven, single-purpose compute service, the most granular and shortest-lived compute unit in GCP's compute spectrum. It fits a narrow niche compared to Cloud Run - a specific triggered action like resizing an uploaded image, rather than a full application with multiple routes and business logic.

Cloud Load Balancing

Google Cloud's family of load balancing products, spanning Global External HTTP(S) Load Balancers (public, distributed globally via a single IP), Regional External Load Balancers, and Internal Load Balancers reachable only from within the VPC. The right type depends on traffic type and whether the backend should ever be reachable from the public internet.

Cloud Logging

Google Cloud's service for collecting, storing, and querying log data from every GCP service and custom applications. Its query filter syntax lets logs be narrowed by resource, severity, and specific field values, and Log Sinks can route matching logs to BigQuery, Cloud Storage, or Pub/Sub for long-term retention beyond the default window.

Cloud Monitoring

Google Cloud's metrics, dashboards, and alerting service. An alert policy requires a Notification Channel explicitly attached to actually notify someone when it fires - without one, the policy still evaluates and logs its own firing history, but nobody is ever told, a common and easy-to-miss misconfiguration.

Cloud NAT

A service providing outbound-only internet connectivity for resources with no external IP address, GCP's equivalent of an AWS or Azure NAT Gateway. Cloud NAT requires a Cloud Router in the same region and provides zero inbound connectivity capability - a resource behind it remains completely unreachable from the internet.

Cloud Run

A fully managed, serverless platform for running containerized applications, scaling automatically to zero when idle and billing only for actual invocations. It combines the flexibility of running any container with zero OS management overhead, making it the right default for a standard stateless containerized web service.

Cloud SQL

Google Cloud's managed relational database service, supporting MySQL, PostgreSQL, and SQL Server. It is the right default for a traditional relational workload with moderate scale needs, handling patching, backups, and replication automatically without requiring OS-level access to the underlying database server.

Cloud Spanner

A globally distributed, strongly consistent relational database offering both SQL semantics and horizontal scalability beyond what a single Cloud SQL instance can provide. It is the right choice specifically when a workload needs both relational query capability and massive scale simultaneously, not simply because a workload feels large or important.

Cloud Storage Bucket

The top-level container for objects in Google Cloud Storage, GCP's object storage service equivalent to AWS S3 or Azure Blob Storage. Every object uploaded to Cloud Storage must belong to exactly one bucket, and bucket-level settings control default storage class, location, and access permissions for everything inside it.

Cloud VPN (GCP)

A service connecting an on-premises network to a GCP VPC over an encrypted tunnel, similar to VPN Gateway in Azure or a Site-to-Site VPN in AWS. It requires a Cloud Router as its foundation and is distinct from VPC Network Peering, which connects two GCP VPCs directly rather than an external network.

Compute Engine

Google Cloud's Infrastructure-as-a-Service offering, providing full virtual machines with complete OS-level control. It is the right choice specifically when a workload needs custom software, specific OS configurations, or hardware-level access that GKE and Cloud Run don't expose.

Error Reporting (GCP)

A Google Cloud operations service that automatically aggregates and groups application errors from logs and instrumented code, surfacing recurring error patterns and their frequency without requiring manual log searching for each individual occurrence.

Firestore

A serverless NoSQL document database built for mobile and web application data, flexible schemas, and real-time client synchronization. It is not a strong fit for workloads needing complex relational joins or multi-row transactions across unrelated entities, which point instead to Cloud SQL or Spanner.

GCP Audit Log

A specific category of Cloud Logging entry recording administrative actions and data access. Admin Activity logs (configuration changes) are always enabled and cannot be disabled; Data Access logs (who read or wrote actual data) are disabled by default for most services and must be explicitly enabled before that history exists.

GCP Firewall Rule

A rule defined at the VPC level controlling inbound or outbound traffic, applied using network tags or Service Accounts on instances rather than being tied to a specific subnet boundary. A firewall rule only affects VMs carrying the exact matching tag or identity - a VM without it is entirely unaffected, silently, with no error to flag the mismatch.

GCP Folder

An optional grouping node in the GCP resource hierarchy, sitting between the Organization and individual Projects. Folders are commonly used to group Projects by team, department, or environment, letting IAM permissions and Organization Policies be applied once at the Folder level rather than repeated across every Project inside it.

GCP IAM Role Types

Google Cloud IAM roles come in three types: Basic roles (Owner, Editor, Viewer) which are broad and legacy; Predefined roles curated by Google and scoped to a specific service's specific needs; and Custom roles built from individual permissions for access needs a predefined role doesn't precisely match.

GCP Organization

The top-level node in Google Cloud's resource hierarchy, tied to a Google Workspace or Cloud Identity domain. An Organization contains Folders and Projects, and policies or IAM permissions set at this level automatically apply to everything beneath it across the entire company.

GCP Project

The fundamental unit of organization in Google Cloud - every resource belongs to exactly one Project, which serves as the boundary for billing, IAM permissions, and API enablement. A Project has a permanent, globally unique Project ID chosen at creation and never changeable, distinct from its display name which can be updated freely.

GCP Quota

A default limit on how much of a specific resource (like VM CPUs or API calls) can be used per Project per region, designed to prevent runaway costs and protect shared infrastructure. Quotas can be checked and increased through the Console ahead of a known future need, such as a planned launch event.

GCP Storage Class

A pricing and access tier for Cloud Storage objects - Standard, Nearline, Coldline, or Archive - trading lower storage cost against higher retrieval cost and a longer minimum storage duration. Deleting or overwriting an object before its class's minimum duration elapses still bills as if it were stored the full minimum period.

GKE Autopilot

A mode of Google Kubernetes Engine where Google manages node provisioning, sizing, and patching entirely - you define workloads, and nodes appear automatically to run them, billed per pod resource request rather than per node. It is the lower-effort default for most containerized workloads, versus Standard mode's direct node pool control.

Managed Instance Group

A group of identical Compute Engine VMs created from an Instance Template and managed as a single unit, GCP's equivalent of an AWS Auto Scaling Group or Azure VM Scale Set. A Managed Instance Group can autoscale based on a metric like CPU utilization, adding or removing instances automatically within configured minimum and maximum bounds.

Network Tag (GCP)

A freeform string label attached to a Compute Engine VM at creation time, used to target firewall rules to specific VMs. Network tags are simple but can be forgotten or misspelled at scale, which is why Service Account-based targeting is often preferred for anything security-critical in a growing fleet.

OS Login

A Compute Engine feature that ties SSH access to a user's actual Google Identity and IAM permissions, rather than manually managing individual SSH public keys per VM. Enabling OS Login means revoking a departing employee's GCP access also immediately revokes their SSH access to every VM, with no separate key cleanup needed.

Organization Policy (GCP)

A constraint applied at the Organization, Folder, or Project level that restricts what resources are allowed to look like across everything beneath that level - for example, blocking external IP addresses on VMs or restricting allowed regions. Unlike IAM, which controls who can act, Organization Policy controls what configurations are permitted.

Persistent Disk (GCP)

The block storage attached to a Compute Engine VM, equivalent to an AWS EBS volume or Azure Managed Disk. Persistent Disks come in zonal (replicated within one zone, lower cost) and regional (synchronously replicated across two zones, survives a single zone failure) variants.

Security Command Center

Google Cloud's security posture management service, continuously scanning deployed resources against security best practices and surfacing specific, severity-ranked findings - like a publicly accessible storage bucket - rather than a single opaque score. Findings should be prioritized by actual severity, not treated as a count to minimize.

Service Account (GCP)

An identity used by applications, VMs, and automated processes to authenticate to Google Cloud APIs, rather than by a human user. A Service Account is itself also a resource with its own IAM permissions, and can be attached directly to a VM or impersonated temporarily, both safer alternatives to downloading its long-lived JSON key file.

Shared VPC

A configuration where one Project (the host) owns a VPC network, while other Projects (service projects) attach to it and deploy resources using its subnets. This centralizes network administration in the host Project while letting individual teams in service Projects still manage their own resources independently.

Spot VM (GCP)

A Compute Engine VM using Google's spare, unused capacity at a steep discount, with the trade-off that Google can reclaim the instance with short notice. Spot VMs are appropriate only for fault-tolerant, interruption-tolerant workloads like batch processing, never for customer-facing services needing reliable availability.

VPC (GCP)

A Virtual Private Cloud in Google Cloud is a global resource by default, unlike the regional VPC or VNet model in AWS or Azure - a single GCP VPC can span every region, with individual subnets defined per-region inside it. The default auto-mode VPC pre-creates a subnet in every region, while a custom-mode VPC starts empty until subnets are deliberately defined.

VPC Network Peering

A direct connection between two separate VPCs, potentially in different Projects or Organizations, with traffic never touching the public internet. Peering must be established from both sides to become active, and is explicitly non-transitive - if VPC A peers with B, and B peers with C, A cannot reach C without its own direct peering connection to C.

Explore More in GCP Storage and Database Solutions

All 6 Topics

Frequently Asked Questions

Is Running Analytics Queries with BigQuery free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Running Analytics Queries with BigQuery topic cover?

Load data, query it with SQL, and use dry runs, partitioning, and byte limits to control BigQuery costs before a query ever runs.

Found a mistake, an outdated step or a broken link?