All The Ways To Connect To BigQuery & Which Is Best

You can’t always work inside BigQuery and you need to do calculations with some more capable language like Python.

In other cases, you want to pull the data once and run multiple queries on that sample without being billed for it.

I show you how to pull the data out from BigQuery so that you can actually expand your analytics capabilities.

Which One Do You Use?

Pick based on where the analysis happens, not on which tool looks cooler. Find your row, then jump to that section.

Short version: ADC on your laptop, a service account on a server and Workload Identity Federation when you can’t keep a key file. Everything else is just picking the right door.

You want toUseLog in withWatch out forJump to
Explore data on your laptopPython with Pandas, Polars or DuckDBADCMissing readSessionUser role (or pass create_bqstorage_client=False)Python
Take a quick look with zero installsGoogle Sheets or a Colab notebookYour Google accountConnected Sheets needs a Google Workspace accountSpreadsheets
Show stakeholders a dashboardData Studio on a modeled tableYour Google accountPoint it at a pre-aggregated table, never at raw eventsDataViz Tools
Run it on a schedulen8n node or the bq CLIService accountKeep the key file out of your repon8n
Run SQL from a terminalbq CLIgcloud loginSet --location when BigQuery can’t infer it, or job lookups and INFORMATION_SCHEMA queries fail with a not found errorbq CLI
Run from CI or another cloudAny client libraryWorkload Identity FederationNeeds a one-time pool and provider setup, but no key file to leakWorkload Identity
Build an appNode.js or SQLAlchemyService accountSQLAlchemy 2.0 needs text() around raw SQLNode.js
Forecast or classify inside pandasbigframes .bigquery accessorADC plus Agent Platform UserSome AI functions call Gemini and others use different models, so check each function’s pricing firstbigframes
Ask questions in plain languageBigQuery MCP serverOAuth with a dedicated identityAllow only execute_sql_readonly, results cap at 3,000 rowsMCP server

BigQuery holds your GA4 and GSC exports, but you rarely want to stay inside the console.

You need the data in Python, in a spreadsheet, in a dashboard or in an automation flow.

Every path in this article does the same thing: authenticate once, then pull data to where your analysis actually happens.

Diagram: BigQuery connects through one login (ADC or service account) to six lanes: code, spreadsheets, dashboards, terminal, automation and AI agents

Before Anything Else: Authentication

Every method in this article has the same prerequisite: proving who you are to Google Cloud.

This is where most people get stuck (and also me sometimes), so let’s get it out of the way first.

Step 0: Do This In The Cloud Console First

Before you touch any code or CLI, you need three things set up in the Google Cloud Console. Most authentication errors happen because one of these is missing.

  1. Create (or select) a project: the project is the container for all your BigQuery data, so use the top left dropdown in the console and click “New Project”.

    Give it a clear name and note the project ID, which looks like my-project-123456 and which you’ll use everywhere.
  2. Enable the BigQuery API: in the console, go to APIs & Services > Library, search “BigQuery API” and enable it.

    Without this, every connection attempt fails with a permissions error even with valid credentials.
  3. Attach a billing account: go to Billing in the console and link a billing account to the project.

    Your own data needs billing once you leave the free sandbox, which runs queries without billing within monthly limits.

    You can set a budget alert if you’re worried about costs.

I’ll also assume you read my article on the BigQuery exports from both GA4 and GSC.

That’s the console part done. From here on, everything happens in your terminal.

Step 1: Install The Google Cloud CLI (gcloud)

Every authentication method below goes through gcloud, the official Google Cloud command line tool.

You need to install it first, it doesn’t come with Python or your OS.

On macOS:

# with homebrew
brew install --cask gcloud-cli

On Windows, download the installer.

On Linux:

# with apt (Debian/Ubuntu), after adding Google's apt repo first
# see https://cloud.google.com/sdk/docs/install#deb
sudo apt install google-cloud-cli

# or the official installer script
curl -O https://dl.google.com/dl/cloudsdk/channels/rapid/downloads/google-cloud-cli-linux-x86_64.tar.gz
tar -xzf google-cloud-cli-linux-x86_64.tar.gz
./google-cloud-sdk/install.sh

Verify it works before continuing:

gcloud --version

Step 2: Log In With Your Google Account (OAuth)

Now you authenticate with your Google account.

This is the OAuth flow: gcloud opens a browser tab, Google asks you to pick an account and grant permissions, while a token gets stored locally on your machine.

gcloud auth login

In the browser tab that opens, grant access with the correct Google account, namely the one that owns (or has access to) the project where your data lives.

Use the same account for everything, mixing accounts between the console and the CLI is a common source of “project not found” errors.

Also set your project explicitly, so you don’t have to pass it in every command:

gcloud config set project my-project-123456

Step 3: Application Default Credentials (ADC)

gcloud auth login is for the gcloud CLI itself.

But the Python library, R and the other client libraries in this article use something else: Application Default Credentials (ADC). They’re separate, so you need to create them too:

gcloud auth application-default login

Run this in your terminal, or as a cell magic in Jupyter if you work in notebooks. Another browser tab opens, with the same account choice.

After this, bigquery.Client() in Python and the R and Node.js clients just work with no extra config.

The bq CLI is the exception: it reuses the gcloud auth login credentials from Step 2. ADC is what you want on your laptop.

Quick way to check everything is wired up:

gcloud auth application-default print-access-token

Service Account Keys (For Automation)

For servers and automation (cron jobs, n8n, a VM), you use a service account instead.

That’s because you don’t want the “interactive” human part, a service account is a non-human identity with its own permissions.

Create one in the Cloud Console: IAM & Admin > Service Accounts > Create Service Account.

Give it a name and assign a role: BigQuery Data Viewer to read tables, BigQuery User to also run queries.

Running a query needs both, since User brings the job permission and Data Viewer brings the data one. Then create a key, download the JSON file and point your code at it:

export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account-key.json

This is the standard for anything that runs unattended.

Keep the key file out of your repo, use environment variables or a secrets manager.

A downloaded key is a long-lived password, so Google recommends avoiding keys where you can: on Google Cloud, attach the service account to the resource (Cloud Run, a VM) and there’s no file to leak.

On your laptop you can skip the key as well, with service account impersonation. You log in as yourself and Google hands you short-lived credentials for the service account.

gcloud auth application-default login --impersonate-service-account=SERVICE_ACCOUNT_EMAIL

Your own account needs the Service Account Token Creator role (roles/iam.serviceAccountTokenCreator) on that service account. After that your code runs with the service account’s permissions and no key file exists anywhere.

If you grant BigQuery Job User instead of User, also add BigQuery Read Session User (roles/bigquery.readSessionUser). BigQuery User already includes it.

The [bqstorage] install below, to_arrow() and the DuckDB extension all read through the Storage Read API, so without that role they fail with bigquery.readsessions.create permission denied.

Google says IAM changes typically take about 2 minutes and can take 7 minutes or longer, so if a permission error survives a fresh grant, wait and run it again before you debug anything else.

Two more things trip people up. Job User goes on the project that runs the query, while Data Viewer goes on the tables it reads, so the two can sit in different projects.

And if a call fails saying the API isn’t enabled or that no quota project is available, your user credentials need a quota project, which Google covers under “User credentials not working” in its ADC setup guide.

Workload Identity Federation (No Key File)

If your job runs outside Google Cloud, for example in GitHub Actions, AWS, Azure or a Kubernetes cluster, you can skip service account keys entirely.

Workload Identity Federation lets the workload exchange a credential from its own identity provider for a short-lived Google token.

The setup happens once (luckily).

You create a workload identity pool, add a provider that describes your identity provider (AWS, Microsoft Entra ID, GitHub, GitLab, Kubernetes clusters outside GKE and Okta are all supported) and then grant the BigQuery roles from above to the federated identity.

Google’s default is granting them directly to that identity, with service account impersonation as the fallback when an API has a limitation.

For GitHub and other shared providers, add an attribute condition (for example on the repository owner) so tokens from other organizations can’t use your pool.

Then you generate a credential configuration file with gcloud iam workload-identity-pools create-cred-config and point GOOGLE_APPLICATION_CREDENTIALS at it.

That file describes how to get a token and contains no private key, so there is nothing long-lived to leak. Google’s AWS and Azure guide walks through the full flow.

Which Login Should You Use?

  • On your laptop, doing ad-hoc analysis: ADC (after gcloud auth application-default login)
  • On a server, scheduled job or automation platform: service account
  • Inside Google Cloud services (Cloud Run, Cloud Functions): built-in service accounts, no key file at all
  • Outside Google Cloud (CI, AWS, Azure): Workload Identity Federation, no key file either

Programming Languages

For local analysis or specific requests, you want to pull a sample of data from BigQuery into your environment.

Luckily there are many libraries that do it for you and you don’t have to spend the rest of your life writing a connector.

Python (Pandas + Polars + DuckDB)

Python is still the most common programming language for this sort of stuff. The official Google Cloud client is the main entry point.

If you’ve been reading Seotistics, you know that Pandas is the most mainstream data package but not the most performing.

Pandas

pip install 'google-cloud-bigquery[bqstorage,pandas]'

The pattern you’ll use 90% of the time: query into a DataFrame. The query runs in BigQuery, only the result comes back to your machine.

If you get a permission error about read sessions, add the role described in the service account section or pass create_bqstorage_client=False to to_dataframe() to use the slower plain API instead.

from google.cloud import bigquery
import pandas as pd

# Initialize client
client = bigquery.Client(project='your-project-id')

# Query data directly into DataFrame
query = """
    SELECT column1, column2, COUNT(*) as count
    FROM `your-project.your-dataset.your-table`
    GROUP BY column1, column2
    ORDER BY count DESC
    LIMIT 1000
"""

df = client.query(query).to_dataframe()
print(df.head())

# You can also read entire tables
df = client.query("SELECT * FROM `your-project.your-dataset.your-table`").to_dataframe()

pandas-gbq and the %%bigquery magic

If all you need is a DataFrame, pandas-gbq is the shortest path. It wraps the same client in one function call.

pip install pandas-gbq
import pandas_gbq

sql = "SELECT event_name, COUNT(*) AS cnt FROM `your-project.analytics_123456789.events_*` WHERE _TABLE_SUFFIX = '20240101' GROUP BY event_name"
df = pandas_gbq.read_gbq(sql, project_id="your-project-id")

In Jupyter you can skip Python code altogether with the %%bigquery cell magic, which lives in its own package.

pip install bigquery-magics
%load_ext bigquery_magics

Then run the query in its own cell, because a cell magic has to be the first line of its cell:

%%bigquery df --project your-project-id
SELECT event_name, COUNT(*) AS cnt
FROM `your-project.analytics_123456789.events_*`
WHERE _TABLE_SUFFIX = '20240101'
GROUP BY event_name

The result lands in a pandas DataFrame called df, using the same ADC credentials from Step 3.

Polars

Polars is the faster choice when your query results are big, because it stays in Arrow format instead of materializing pandas objects.

pip install google-cloud-bigquery polars

Same client as before, with one extra step: convert the Arrow result into a Polars DataFrame.

import polars as pl
from google.cloud import bigquery

client = bigquery.Client()

# Perform a query.
QUERY = (
    'SELECT name FROM `bigquery-public-data.usa_names.usa_1910_2013` '
    'WHERE state = "TX" '
    'LIMIT 100')
query_job = client.query(QUERY)  # API request
rows = query_job.result()  # Waits for query to finish

df = pl.from_arrow(rows.to_arrow())

DuckDB

DuckDB is the local analytical database that everyone is talking about. It reads Parquet and Arrow natively, which pairs perfectly with the Arrow format BigQuery returns.

The cleanest path is to pull the query result as Arrow, then hand it to DuckDB for fast local analysis:

pip install google-cloud-bigquery duckdb
import duckdb
from google.cloud import bigquery

client = bigquery.Client()

query = """
    SELECT event_name, COUNT(*) as cnt
    FROM `your-project.analytics_123456789.events_*`
    WHERE _TABLE_SUFFIX BETWEEN '20240101' AND '20240131'
    GROUP BY event_name
    ORDER BY cnt DESC
"""

df = client.query(query).to_arrow()
result = duckdb.sql("SELECT * FROM df LIMIT 100").df()
print(result)

There’s also a DuckDB BigQuery extension that skips the Python client entirely. It’s a community extension, installed from the community repository:

INSTALL bigquery FROM community;
LOAD bigquery;
ATTACH 'project=your-gcp-project' AS bq (TYPE bigquery, READ_ONLY);

After that, query BigQuery tables with plain DuckDB SQL. Handy when you want one SQL dialect for everything.

R

For the few people that use R, the process is the same as Python since they are programming languages (duh). The bigrquery package handles connection and downloads, using the same ADC credentials from Step 3.

Install the required libraries:

install.packages("bigrquery")
install.packages("DBI")

Then run this:

library(bigrquery)
library(DBI)

# Set up connection
project_id <- "your-project-id"
dataset_id <- "your-dataset"

# Query data
sql <- "SELECT * FROM `your-project.your-dataset.your-table` LIMIT 1000"
df <- bq_project_query(project_id, sql) |>
  bq_table_download()

# Alternative using DBI interface
con <- dbConnect(
  bigrquery::bigquery(),
  project = project_id,
  dataset = dataset_id
)

df <- dbGetQuery(con, sql)

Spreadsheets

In some cases you want to pull specific data straight into a spreadsheet.

Google Sheets make it easier, Excel… not really.

Google Sheets

Google Sheets has a native BigQuery connector that’s the easiest way to pull data directly into spreadsheets.

PS: Connected Sheets needs a Google Workspace account (it’s included in the Business, Enterprise and Education editions) and a Google Cloud project with billing enabled.

Steps:

  1. Open Google Sheets and go to Data > Data connectors > Connect to BigQuery
  2. Select your Google Cloud project
  3. Choose your dataset and table, or write a custom SQL query
  4. Configure refresh settings and data range
  5. Click Connect

The data will populate in your sheet and can be refreshed automatically or manually.

This method is perfect for dashboards and reports that need to stay current.

Apps Script (Google Sheets/Docs)

Query BigQuery directly from Google Sheets using Apps Script. First enable the BigQuery service: in the Apps Script editor, click the + next to Services and add BigQuery API.

function queryBigQuery() {
  const projectId = 'your-project-id';
  const query = `
    SELECT 
      date,
      SUM(sessions) as sessions
    FROM \`analytics_123456789.daily_summary\`
    WHERE date >= DATE_SUB(CURRENT_DATE(), INTERVAL 30 DAY)
    GROUP BY date
    ORDER BY date
  `;
  
  const request = {
    query: query,
    useLegacySql: false
  };
  
  const queryResults = BigQuery.Jobs.query(request, projectId);
  const rows = queryResults.rows;
  
  // Write to sheet
  const sheet = SpreadsheetApp.getActiveSheet();
  const values = rows.map(row => [
    row.f[0].v, // date
    row.f[1].v  // sessions
  ]);
  
  sheet.getRange(2, 1, values.length, values[0].length).setValues(values);
}

Use cases:

  • Automated report generation in Sheets
  • Custom sidebar tools in Google Workspace
  • Scheduled data refreshes without leaving Sheets

Excel

There’s no official BigQuery button inside Excel, whatever some posts claim. The supported route is Google’s BigQuery ODBC driver, reached through Power Query.

What? Do people actually use Excel for this?

Well, if you really want to pull your data out of BigQuery and into Excel, this is more or less the process:

  1. Download and install the Simba ODBC driver
  2. Configure ODBC data source with your GCP credentials
  3. In Excel: Data > Get Data > From Other Sources > From ODBC
  4. Select your configured BigQuery data source
  5. Write SQL or select tables
  6. Load data to worksheet

DataViz Tools

This is the layer your stakeholders actually see, so it deserves its own section.

Please, remember that the following tools are your presentation layer. This means you use them to present your data and NOT to apply transformations or for complex business logic.

This is where you notice the difference between a good data model and a bad one (or none at all).

Data Studio

Data Studio has native BigQuery integration and is the go-to for dashboards.

Steps:

  1. Create a new report or open an existing one
  2. Click “Add Data” > “BigQuery”
  3. Choose your project, dataset and table OR
  4. Write a custom SQL query (if needed)
  5. Configure any parameters or date range variables
  6. Click “Add”

Key features:

  • Direct connection (no data copying)
  • Query results cached for performance
  • Can blend BigQuery data with other sources
  • Automatic refresh on dashboard load

Tips:

  • Use custom queries to pre-aggregate data (faster dashboards). Even better, work on your data model
  • Add date range parameters for filtering
  • Materialize complex queries as BigQuery tables for better performance

PowerBI

Power BI has decent BigQuery integration for analytics dashboards.

Microsoft is also moving this connector from ODBC to ADBC drivers, which you opt into per connection with Implementation="2.0".

Steps:

  1. In Power BI Desktop: Get Data > More > Google BigQuery
  2. Select your GCP project
  3. Choose “DirectQuery” or “Import” mode
  4. Navigate to your dataset and tables
  5. Load or transform data

DirectQuery vs Import:

  • DirectQuery: Queries BigQuery in real-time (slower, always current)
  • Import: Copies data to Power BI (faster, requires refresh)

For web analytics data, Import mode with scheduled refreshes usually works better.

DirectQuery can be painfully slow for the massive amount of data we deal with.

Tableau

Tableau connects to BigQuery through a native connector. Pick Google BigQuery (JDBC), since the older “Google BigQuery” connector is legacy.

Steps:

  1. Open Tableau Desktop
  2. Connect > Google BigQuery (JDBC)
  3. Enter the billing project ID, the project that gets billed for the queries
  4. Sign in with OAuth or a service account JSON key
  5. Pick the project, dataset and table

Connection modes:

  • Live: Queries BigQuery directly, which is what Tableau recommends for BigQuery
  • Extract: Copies the data into a local .hyper file

Tableau’s own docs say BigQuery datasets are large and to connect live. I’d only use an extract on a small, pre-aggregated table, since every extract refresh runs a query you pay for.

CLI Tools

Real analysts work on terminals for automating tasks or for a higher level of precision.

And querying your BQ data can be one of these tasks.

bq command-line tool

The official BigQuery CLI tool comes with the Google Cloud SDK.

# Install Google Cloud SDK first
# Then authenticate
gcloud auth login

# Run queries
bq query --use_legacy_sql=false \
'SELECT 
  event_name,
  COUNT(*) as event_count
FROM `your-project.analytics_123456789.events_*`
WHERE _TABLE_SUFFIX BETWEEN "20240101" AND "20240131"
GROUP BY event_name
ORDER BY event_count DESC'

# Set the location when BigQuery can't infer it (job lookups, INFORMATION_SCHEMA)
bq --location=EU query --use_legacy_sql=false \
'SELECT COUNT(*) FROM `your-project.analytics_123456789.events_20240101`'

# Export to CSV
bq query --use_legacy_sql=false \
  --format=csv \
  --max_rows=100000 \
  'SELECT * FROM `project.dataset.table`' > output.csv

# Export a table to Cloud Storage (extract writes to a bucket, not your laptop)
bq extract \
  --destination_format=CSV \
  project:dataset.table \
  gs://bucket-name/file.csv

Use cases:

  • Automation scripts
  • Scheduled data exports
  • Quick ad-hoc queries from terminal

Gemini CLI

Gemini CLI is Google’s terminal agent. With the BigQuery Data Analytics extension it can answer questions about your warehouse straight from the command line.

Google’s own update says that from June 18, 2026 Gemini CLI stops serving free, Google AI Pro and Ultra accounts, with Antigravity CLI as the replacement.

Extensions carry over as Antigravity plugins, so check that the BigQuery one is available there before you build on it.

LLMs are getting much better BUT since the output is non-deterministic (aka black box), be careful and double check.

The key advice here is to provide a list of sample queries and routines so Gemini has less freedom to make stuff up.

BigQuery MCP Server

Google hosts an official remote MCP server for BigQuery, so an AI agent can list datasets, read schemas and run SQL without you writing a connector.

It switches on when you enable the BigQuery API, so the endpoint is https://bigquery.googleapis.com/mcp.

Any MCP client that supports remote servers can connect: use the Streamable HTTP transport, the endpoint above and the OAuth scope https://www.googleapis.com/auth/bigquery.

The identity behind the client needs three IAM roles on the project: MCP Tool User (roles/mcp.toolUser), BigQuery Job User and BigQuery Data Viewer.

Google recommends a separate identity for agents, which in practice means a dedicated service account with nothing else attached.

Only one tool can write, execute_sql. execute_sql_readonly blocks DML and DDL, while you can deny execute_sql completely with an IAM deny policy for read-write MCP tools.

Queries are cancelled after three minutes and results are capped at 3,000 rows, so it’s built for questions and spot checks, not for pulling a table into Python.

The same warning as Gemini CLI applies, since the model writes the SQL and the output is non-deterministic.

If you can’t enable the remote server in your project, or you want a custom tool over a parameterized query, Google also offers a local MCP server through MCP Toolbox.

However, I generally avoid MCPs as carefully explained in my MCP VS API comparison.

Node.js / JavaScript

For server-side JavaScript or automation, there’s an official @google-cloud/bigquery client, although its GitHub repository was archived in February 2026 with a deprecation notice.

So check the package page before you start a new project. It reads the same service account or ADC credentials as everything else.

const {BigQuery} = require('@google-cloud/bigquery');

// Create client
const bigquery = new BigQuery({
  projectId: 'your-project-id',
  keyFilename: 'path/to/service-account-key.json' // or drop this line to use default credentials
});

async function queryData() {
  const query = `
    SELECT 
      event_name,
      COUNT(*) as count
    FROM \`your-project.analytics_123456789.events_*\`
    WHERE _TABLE_SUFFIX = FORMAT_DATE('%Y%m%d', CURRENT_DATE())
    GROUP BY event_name
    ORDER BY count DESC
    LIMIT 10
  `;

  const [rows] = await bigquery.query(query);
  console.log('Rows:');
  rows.forEach(row => console.log(row));
}

queryData();

Use cases:

  • Web apps that need BigQuery data
  • Serverless functions (Cloud Functions, AWS Lambda)
  • Automation workflows (n8n, Make)

Others

Everything that doesn’t fit a clean category, including the paths I use most for automation.

Notebooks (Colab / BigQuery Studio)

Notebooks are the fastest way to start, especially if you’re new to this. Google Colab ships with the BigQuery client already installed, you just log in and name your project:

from google.colab import auth
auth.authenticate_user()  # opens a Google login, only needed in Colab

from google.cloud import bigquery

client = bigquery.Client(project='your-project-id')
df = client.query("SELECT * FROM `bigquery-public-data.samples.gsod` LIMIT 100").to_dataframe()
df.head()

BigQuery Studio (inside the BigQuery console) also has native notebooks now, which keeps everything in one place with no setup at all. Great for exploring before you build something permanent.

n8n (The Automation Path)

For SEO and analytics automation, n8n has a native Google BigQuery node.

You drop it into a workflow, authenticate once with a service account, then you can run queries or insert rows as part of a pipeline.

This is how I run scheduled analyses: a cron trigger fires an n8n workflow, it queries BigQuery, sends the result to an LLM for interpretation and saves the output. No script to babysit, it just runs on the server.

BigQuery DataFrames (bigframes)

If you like the pandas API but don’t want to pull data out of BigQuery, bigframes pushes pandas operations down to BigQuery, so the heavy work runs in the warehouse and only the result comes back when you call to_pandas(). That matters when your tables are huge.

pip install bigframes
import bigframes.pandas as bpd

df = bpd.read_gbq("your-project.your-dataset.your-table")
result = df.groupby("event_name")["event_count"].sum().to_pandas()
print(result)

The new .bigquery accessor: AI functions on plain pandas

Google just added a .bigquery accessor to bigframes (announced November 6, 2026).

It lets you call BigQuery AI functions on a regular pandas DataFrame or Series, including data that sits in a local CSV. Importing bigframes.pandas is what enables it, while the work runs in BigQuery, not on your machine; the result comes back as a standard pandas object.

Setup is the same project option as above, plus two IAM roles on the project: BigQuery Job User (roles/bigquery.jobUser) to run query jobs and Agent Platform User (roles/aiplatform.user) to reach the foundation models. If you own the project you already have both.

import pandas as pd
import bigframes.pandas as bpd  # enables the .bigquery accessor

bpd.options.bigquery.project = "my-project"

animals = pd.Series(["dog", "fish"])
animals.bigquery.ai.similarity("shrimp", endpoint="text-embedding-005")

The same pattern covers forecasting on a DataFrame, with no model to train:

df.bigquery.ai.forecast(
    data_col="sales",
    timestamp_col="date",
    id_cols=["item_id"],
    horizon=3
)

Series functions are embed(), generate_embedding(), generate_table(), generate_text() and similarity().

DataFrame functions are classify(), forecast(), generate(), generate_bool(), generate_double(), generate_int(), if_(), predict() and score().

For web analytics, forecast() on daily sessions and classify() on page titles or queries are the obvious first tests. Full details in the announcement post.

SQLAlchemy / Ibis

If you’re building an application, the standard Python pattern is SQLAlchemy with the sqlalchemy-bigquery dialect. It gives you ORM-style access and plays well with frameworks.

pip install sqlalchemy-bigquery
from sqlalchemy import create_engine, text

engine = create_engine("bigquery://your-project/your-dataset")
with engine.connect() as conn:
    rows = conn.execute(text("SELECT * FROM your_table LIMIT 10"))
    for row in rows:
        print(row)

More DataViz Options

Data Studio, Power BI and Tableau aren’t the only options. If you want something lighter or cheaper:

  • Metabase: open source, self-hosted, connects to BigQuery easily
  • Grafana: best for monitoring and time-series dashboards, has a BigQuery plugin
  • Apache Superset: open source BI with a BigQuery connection, good for heavier analytics

Cost & Limits: Read This Before You Pull

A few rules that will save you money and headaches:

  • Select only the columns you need: BigQuery bills for the bytes in the columns it reads, so LIMIT doesn’t change that.

    A SELECT * with LIMIT 10 on a table that isn’t clustered still scans the whole table, since LIMIT only caps how many rows come back, so check whether yours is clustered before you count on it to save money.
  • Use _TABLE_SUFFIX filters on sharded tables (events_*) to scan only the days you need.
  • Prefer Arrow over JSON for Python: to_arrow() is faster and lighter on memory than row-by-row JSON conversion. It doesn’t change the query cost, which is decided by the bytes scanned.
  • DirectQuery/Import matters: in BI tools, Import mode copies data once (predictable cost), DirectQuery runs a query per interaction (can get expensive).

Before you run anything on a big table, do a dry run, which returns the bytes the query would scan without running it or billing you. You can also set a hard cap so an expensive query fails instead of charging you:

from google.cloud import bigquery

client = bigquery.Client()
sql = "SELECT event_name FROM `your-project.analytics_123456789.events_*` WHERE _TABLE_SUFFIX BETWEEN '20240101' AND '20240131'"

# 1. Dry run: estimate the scan, nothing is executed or billed
dry = client.query(sql, job_config=bigquery.QueryJobConfig(dry_run=True, use_query_cache=False))
print(f"{dry.total_bytes_processed / 1e9:.2f} GB would be processed")

# 2. Hard cap: the job fails if it would bill more than 10 GB
capped = bigquery.QueryJobConfig(maximum_bytes_billed=10 * 1024**3)
df = client.query(sql, job_config=capped).to_dataframe()

Using curl with gcloud auth

No library required. Grab a token and call the REST API directly:

ACCESS_TOKEN=$(gcloud auth application-default print-access-token)

curl -X POST \
https://bigquery.googleapis.com/bigquery/v2/projects/YOUR_PROJECT_ID/queries \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"query": "SELECT COUNT(*) as count FROM `project.dataset.table`",
"useLegacySql": false
}'

Use cases:

  • Custom integrations
  • Platforms without BigQuery libraries
  • Webhook-based workflows

Leave a Comment