BigQuery knowledge base
These 127 articles explain how BigQuery handles cost, storage, SQL, writing data, scripting, performance, security and operations. Every example was checked on BigQuery, and you can run it in the browser.
These articles explain what is specific to BigQuery: how it bills a query, how partitioning and nested data work, which SQL behaves differently from other databases, and the limits you run into. They are based on Google's BigQuery documentation, rewritten and tested: every example on these pages was run on BigQuery, and the result you see is BigQuery's answer. On a desktop browser you can edit an example and run it on Querylab.io's BigQuery engine without an account.
New to BigQuery? Start with How BigQuery works and How a query is billed. To learn by doing, take the 69 free lessons on learn.querylab.io, which check every answer and run in your browser.
Start here
- Getting started with BigQuery: what to do first Project owners set quotas, location, access and defaults before the team arrives.
- Setting up BigQuery: the project owner checklist A new BigQuery project allows 200 TiB of queries a day by default, budgets only warn, and the location can't be changed later.
- Starting with BigQuery as an analyst: the first-week checklist Before your first real BigQuery queries, check which project pays and what access you have.
Basics
- BigQuery updates Google's BigQuery release notes since 2011, cut to the changes a SQL user can act on.
- How BigQuery works BigQuery keeps storage and compute separate, stores each column on its own, and runs a query as parallel stages on slots.
- How BigQuery SQL differs from other SQL BigQuery SQL (GoogleSQL) uses backticks for names, has no implicit string-to-number casts, only one integer type, and requires ALL or DISTINCT after UNION.
- Projects, datasets and tables in BigQuery A BigQuery table is named project.dataset.table.
- BigQuery locations and regions Every BigQuery dataset has one location, a region like europe-west1 or a multi-region like US or EU, and a query runs in the location of the data it reads.
- BigQuery jobs Every query, load, export and copy in BigQuery runs as a job with an ID, a state and a project that is billed.
Cost and pricing
- How BigQuery bills a query On-demand BigQuery charges for the bytes in the columns a query reads, not for rows returned or time spent.
- BigQuery on-demand vs capacity pricing (editions) On-demand BigQuery charges per TiB of data a query reads.
- BigQuery slots explained A BigQuery slot is a unit of compute that runs part of a query.
- BigQuery reservations, commitments and assignments In BigQuery capacity pricing, a commitment buys slots for a term, a reservation is a pool of slots, and an assignment tells a project, folder or organization which reservation to use.
- BigQuery storage pricing: active, long-term, logical and physical BigQuery bills stored data per GiB-month at an active or long-term rate, measured in logical or physical bytes.
- BigQuery query cache BigQuery keeps each query result for about 24 hours and returns it for free when the same query runs again.
- Controlling BigQuery costs: dry runs, byte limits, quotas and partition filters Dry runs, maximum bytes billed, require_partition_filter, custom daily quotas, reservation limits and billing budgets each cap BigQuery cost in a different way.
- BigQuery free tier and sandbox BigQuery gives every account 1 TiB of query processing and 10 GiB of storage free each month, and the sandbox lets you use it without a credit card.
Tables and storage
- BigQuery table types BigQuery has standard tables, external tables, views, materialized views, snapshots, clones and temporary tables.
- BigQuery data types BigQuery has one integer type (INT64), exact decimals (NUMERIC, BIGNUMERIC) and an approximate FLOAT64.
- Nested and repeated data in BigQuery BigQuery stores child rows inside the parent row as a STRUCT or an ARRAY of STRUCTs, so related data needs no join.
- Partitioned tables in BigQuery A partitioned BigQuery table is split by a date, timestamp or integer column.
- Clustered tables in BigQuery A clustered BigQuery table keeps rows with similar values in up to four columns stored together, so a filter on those columns reads fewer blocks.
- Partitioning vs clustering in BigQuery Partition a BigQuery table when queries filter on a date and you need a firm cost estimate.
- Wildcard tables and _TABLE_SUFFIX in BigQuery A wildcard table queries many similarly named BigQuery tables as one, and _TABLE_SUFFIX chooses which of them are read.
- Primary and foreign keys in BigQuery BigQuery primary and foreign keys are not enforced: duplicates and orphans go in without an error.
- Default values and identity columns in BigQuery A DEFAULT value fills a column that an INSERT leaves out.
- Schema changes in BigQuery tables ALTER TABLE changes a schema without rewriting data, so it can add a column at the end, relax REQUIRED to NULLABLE, widen a few types, and rename or drop a column.
- Time travel and fail-safe in BigQuery BigQuery keeps changed and deleted data for 2 to 7 days (7 by default) and lets you query it with FOR SYSTEM_TIME AS OF.
- Table snapshots and table clones in BigQuery A BigQuery table snapshot is a read-only copy that you keep as long as you like.
- Table and partition expiration in BigQuery BigQuery can delete tables and partitions on a schedule.
- Dataset replication and disaster recovery in BigQuery A BigQuery multi-region keeps your data in one region and gives no protection from a regional outage.
Querying
- NULL in BigQuery BigQuery rejects x = NULL with an error instead of returning no rows, refuses NULL elements in arrays it writes, and has IS NOT DISTINCT FROM for NULL-safe equality.
- Arrays in BigQuery BigQuery arrays can't contain arrays or NULLs and can't be compared with =.
- UNNEST in BigQuery UNNEST turns an array into rows.
- STRUCT in BigQuery A STRUCT groups named fields into one value, like a row inside a column.
- JSON in BigQuery BigQuery has a native JSON type with dot access, and JSON_VALUE / JSON_QUERY functions for JSON stored as text.
- DATE, DATETIME, TIMESTAMP and time zones in BigQuery TIMESTAMP is an instant in UTC, DATETIME is a wall-clock time with no zone, DATE is a calendar day.
- INTERVAL and RANGE types in BigQuery INTERVAL stores a duration as months, days and time separately, so 36 hours stays 36 hours until you justify it.
- CAST and type conversion in BigQuery In BigQuery, CAST to INT64 rounds half away from zero, only 'true' and 'false' become BOOL, and FLOAT64 sums aren't exact.
- SAFE_CAST, SAFE_DIVIDE and the SAFE. prefix in BigQuery One bad value stops a whole BigQuery query.
- UNION, INTERSECT and EXCEPT in BigQuery In BigQuery, UNION must say ALL or DISTINCT, INTERSECT and EXCEPT only support DISTINCT, columns match by position unless you add CORRESPONDING or BY NAME, and NULLs count as equal.
- Aggregate functions in BigQuery Beyond SUM and COUNT, BigQuery has COUNTIF, LOGICAL_AND, MAX_BY, ANY_VALUE ...
- GROUP BY, ROLLUP, CUBE and GROUPING SETS in BigQuery BigQuery's GROUP BY accepts SELECT aliases, column numbers and GROUP BY ALL, and computes subtotals with ROLLUP, CUBE and GROUPING SETS.
- Joins in BigQuery In BigQuery, USING merges the key column, and NULL keys never match unless you use IS NOT DISTINCT FROM.
- Subqueries in BigQuery Scalar, ARRAY, STRUCT, IN and EXISTS subqueries in BigQuery.
- CTEs in BigQuery A CTE is a named subquery in a WITH clause.
- DISTINCT in BigQuery SELECT DISTINCT treats NULLs as equal, accepts arrays and structs but refuses JSON and GEOGRAPHY, and bills the same bytes as a plain SELECT.
- CASE, IF and COALESCE in BigQuery CASE branches must share a type, CASE x WHEN NULL never matches, and IF treats a NULL condition as false.
- Hashing, deterministic sampling and A/B buckets in BigQuery FARM_FINGERPRINT gives a fast, stable INT64 hash for bucketing users, splitting A/B tests and finding duplicate rows.
- Legacy SQL vs GoogleSQL in BigQuery In BigQuery legacy SQL a comma between tables means UNION ALL, COUNT(DISTINCT) is approximate, and tables are written [project:dataset.table].
- GEOGRAPHY and spatial functions in BigQuery BigQuery's GEOGRAPHY type is a set of points, lines and polygons on a sphere, with edges that follow great circles and distances in meters.
- SEARCH function and search indexes in BigQuery SEARCH checks whether every term of a query appears as a token in your text or JSON.
- Vector search in BigQuery VECTOR_SEARCH finds the nearest embeddings in a table by Euclidean, cosine or dot product distance.
- Graph queries in BigQuery (GQL and CREATE PROPERTY GRAPH) BigQuery Graph lets you define a property graph over existing tables and query it with GQL or GRAPH_TABLE.
- Window functions in BigQuery With ORDER BY, a BigQuery window's default frame is RANGE up to the current row.
- PIVOT and UNPIVOT in BigQuery BigQuery has PIVOT and UNPIVOT operators in the FROM clause.
- Recursive CTEs in BigQuery WITH RECURSIVE in BigQuery needs UNION ALL, one self-reference, the same column types in both terms, and stops with an error after 500 iterations.
- Pipe syntax in BigQuery BigQuery pipe syntax writes a query as a chain of |> steps in execution order, starting with FROM.
- Strings, regular expressions and collation in BigQuery BigQuery compares strings byte for byte, so Apple and apple differ and Z sorts before a.
- Approximate aggregation and HLL sketches in BigQuery APPROX_COUNT_DISTINCT, APPROX_QUANTILES and APPROX_TOP_COUNT trade a small error for speed on large data.
- TABLESAMPLE in BigQuery TABLESAMPLE SYSTEM reads a random percentage of a table's storage blocks, and on-demand queries are billed only for the blocks read.
- Query parameters in BigQuery BigQuery query parameters are named (@name) or positional (?), carry a type, and replace values only, never table or column names.
- QUALIFY in BigQuery QUALIFY filters rows on the result of a window function, the way HAVING filters on an aggregate.
- Reusable column aliases in BigQuery With reusable column aliases on, a SELECT alias can be used by later SELECT items and the WHERE of the same query.
Writing data
- INSERT, UPDATE and DELETE in BigQuery BigQuery DML needs a WHERE clause on every UPDATE and DELETE, rejects an UPDATE that matches a row twice, bills a filtered UPDATE or DELETE for the whole table, and runs at most two mutating statements per table at once.
- MERGE in BigQuery MERGE updates, inserts and deletes in one statement, which is how you upsert in BigQuery.
- CREATE TABLE, ALTER and DROP in BigQuery BigQuery DDL runs as a query job.
- Loading data into BigQuery Batch load jobs are free and accept CSV, JSON, Avro, Parquet and ORC.
- Loading CSV into BigQuery Load a CSV with bq load, a schema and --skip_leading_rows=1.
- Loading JSON into BigQuery BigQuery loads newline-delimited JSON, one object per line.
- Loading Parquet into BigQuery BigQuery reads the schema from a Parquet file, so a load needs no schema.
- Loading Avro into BigQuery BigQuery reads the schema from an Avro file.
- Loading Excel files into BigQuery BigQuery has no Excel load format.
- Streaming data into BigQuery The Storage Write API streams rows into BigQuery so they can be queried within seconds.
- Change data capture in BigQuery BigQuery CDC applies streamed UPSERT and DELETE rows to a table by primary key, in the background.
- Exporting data from BigQuery Extract jobs copy a table to Cloud Storage for free; EXPORT DATA writes a query's result and is billed as a query.
Scripting and routines
- Scripting and multi-statement queries in BigQuery A BigQuery script is several statements run as one job, with variables, IF, loops, error handling and dynamic SQL.
- Temporary tables in BigQuery CREATE TEMP TABLE works only in a script or a session, takes an unqualified name, and keeps the table (and its storage bill) for up to 24 hours unless you drop it.
- Transactions in BigQuery BEGIN TRANSACTION ...
- Sessions in BigQuery A BigQuery session keeps temp tables, variables, temporary functions and settings like @@time_zone between separate queries, for up to 24 hours of inactivity.
- User-defined functions in BigQuery (SQL, JavaScript and Python) BigQuery UDFs come in SQL, JavaScript and Python.
- Table functions in BigQuery A table function is a parameterized view, a stored query you call in FROM with arguments.
- Stored procedures in BigQuery A BigQuery stored procedure is a saved script you run with CALL.
- Remote functions in BigQuery A remote function calls your own Cloud Run service from SQL, sending rows in batches as JSON.
Views
- Views in BigQuery A BigQuery view is a saved query.
- Materialized views in BigQuery A materialized view stores the result of an aggregation query and keeps it fresh.
- Authorized views, datasets and routines in BigQuery An authorized view lets people query a slice of a table without any access to the table.
Performance
- How a BigQuery query runs BigQuery turns a query into stages that exchange data through shuffle.
- BigQuery performance best practices: how to debug a slow query To debug a slow BigQuery query, first find out what kind of slow it is, then read the execution plan.
- Optimizing joins in BigQuery A slow BigQuery join usually has rows that multiply, skew or a hidden cross join, and the execution plan shows which.
- BigQuery BI Engine BI Engine is an in-memory cache for BigQuery tables that you rent by the gibibyte.
Security and governance
- BigQuery access control and IAM roles BigQuery IAM decides who can read, change and bill queries.
- Row-level security in BigQuery A BigQuery row access policy filters rows per user, with a grantee list or SESSION_USER().
- Column-level security and data masking in BigQuery A BigQuery policy tag restricts a column to some users.
- Encryption in BigQuery BigQuery encrypts all data at rest by default.
- Differential privacy in BigQuery SELECT WITH DIFFERENTIAL_PRIVACY adds noise to aggregates and drops small groups, so a result can't reveal one person.
Sharing
- BigQuery sharing (Analytics Hub) explained BigQuery sharing, formerly Analytics Hub, lets you share a dataset with other projects and organizations without copying it.
- BigQuery data clean rooms and analysis rules A BigQuery data clean room lets several parties query each other's data without seeing the raw rows.
Metadata and operations
- INFORMATION_SCHEMA in BigQuery INFORMATION_SCHEMA views describe tables, columns, partitions, jobs and storage, queried with SQL.
- Monitoring BigQuery jobs and costs with INFORMATION_SCHEMA.JOBS Ready-to-run queries on INFORMATION_SCHEMA.JOBS for cost per user, the most expensive queries, repeated queries, cache hit rate, failures, the tables that cost the most, and slot usage over time, plus the traps that double-count script jobs.
- Labels, billing export and cost attribution in BigQuery Job labels reach BigQuery billing data, dataset labels reach only storage billing, and table labels never do.
- BigQuery audit logs explained BigQuery writes Admin Activity and Data Access audit logs to Cloud Logging, with Data Access logs on by default.
- BigQuery quotas and limits that matter BigQuery allows 1,500 writes per table per day, 5 metadata updates per table per 10 seconds, 2 concurrent UPDATEs per table and 10,000 partitions.
- Common BigQuery errors and how to fix them This page explains the BigQuery error messages people hit most, such as "Unrecognized name", "neither grouped nor aggregated", "Cannot access field on a value with type ARRAY", "Resources exceeded" and "Query exceeded limit for bytes billed", and how to fix each one.
- Scheduled queries in BigQuery Scheduled queries run SQL on a schedule through the Data Transfer Service, with @run_time and @run_date parameters for incremental loads.
- Continuous queries in BigQuery A continuous query processes rows as they land in a table and writes results to another table, Pub/Sub, Bigtable or Spanner.
External data
- External tables in BigQuery An external table queries files in Cloud Storage, Drive or Bigtable without loading them.
- Google Sheets and BigQuery BigQuery queries a Google Sheet in place through an external table, or you copy it into a native table.
- BigLake and Apache Iceberg tables in BigQuery BigLake tables read files in Cloud Storage or other clouds through a connection, so users need access to the table only and row- and column-level security work.
- Federated queries in BigQuery (Cloud SQL, Spanner, AlloyDB) EXTERNAL_QUERY sends SQL to Cloud SQL, AlloyDB or Spanner and returns the result to BigQuery.
- Object tables in BigQuery An object table lists the files in a Cloud Storage bucket as rows, with their metadata, so you can filter them in SQL and send their contents to AI and ML functions.
Google Analytics 4
- GA4 export to BigQuery Google Analytics 4 exports one events_YYYYMMDD table per day, with parameters in a repeated STRUCT.
- GA4 event_params in BigQuery GA4 stores event parameters as a repeated STRUCT of key and typed values.
- GA4 sessions in BigQuery The GA4 export has no sessions table.
- GA4 ecommerce data in BigQuery Purchases in the GA4 export are events with an ecommerce record and a repeated items array.
- GA4 funnels in BigQuery Build a GA4 funnel by turning events into one row per session, with a flag for each stage.
- GA4 attribution in BigQuery The GA4 export has three traffic source records.
- GA4 retention in BigQuery Day-N retention from the GA4 export is the share of a cohort active N days after its first day.
AI and ML
- BigQuery ML in SQL BigQuery ML trains and runs models with CREATE MODEL and ML.PREDICT.
- AI functions in BigQuery (AI.GENERATE, AI.IF, AI.CLASSIFY) BigQuery calls Gemini from SQL with AI.GENERATE, AI.IF, AI.CLASSIFY, AI.SCORE and others.
- Time-series forecasting in BigQuery BigQuery forecasts time series two ways.
Tools and APIs
- The BigQuery Storage Read API The Storage Read API streams table data out of BigQuery in parallel, in Arrow or Avro, with column and row filters, for Spark, pandas and other engines.
- BigQuery DataFrames (bigframes) explained BigQuery DataFrames is a pandas-style Python library that turns your code into SQL and runs it in BigQuery.
- BigQuery and BI tools - Connected Sheets, Data Studio, Looker, Tableau Every BI tool sends real query jobs to BigQuery, and each refresh of a dashboard can bill.
- BigQuery Data Transfer Service explained The BigQuery Data Transfer Service loads data into BigQuery on a schedule from SaaS apps, Google ad and analytics products, other clouds and other warehouses.
- Migrating to BigQuery from Snowflake, Redshift, Teradata and Oracle The BigQuery Migration Service assesses a warehouse, translates SQL from about twenty dialects into GoogleSQL, and moves data.
- Gemini in BigQuery - what each feature does and what it costs Gemini in BigQuery covers SQL and Python assistance, data insights, data canvas, data preparation, conversational analytics with data agents, and a pipeline agent.