Tags: analytics platform

BigQuery

Checked: 2026-10-29


Google’s serverless warehouse: storage and compute are separate services, data is stored by column, and you pay for what a query reads (or for the compute you reserve), never for a server. Every cost and performance habit follows from “how many bytes does this touch”.


§0 The one idea

There is no database server. There is a pile of columns, and a pool of compute you borrow per query.

BigQuery is Google Cloud’s managed analytical warehouse. Compute is measured in virtual CPUs (central processing units), but you never see one: you never size a machine, add an index or tune a buffer pool. Data sits in a distributed storage layer in a columnar format; a query is split into stages and run across however many workers it needs, reading only the columns it names, then the workers go back to the pool.

vs Postgres/MySQL: those are OLTP (online transaction processing) databases — one server, rows stored together, B-tree indexes, built to fetch or update a handful of rows in milliseconds. BigQuery is OLAP (online analytical processing) — built to scan billions of rows and aggregate a few columns. The trade runs both ways: no index to fetch one row fast, no enforced keys, DML (data manipulation language — INSERT/UPDATE/DELETE) that works but is billed and quota’d like a scan — SQL vs NoSQL, Indexing.

POSTGRES / MYSQL                       BIGQUERY
────────────────                       ────────
one server: disk + CPU + RAM           storage  ←─ network ─→  compute
rows stored together                   columns stored apart
                                         │                       │
  row 1: id|name|email|...               │ col: event_name        │ slots, borrowed
  row 2: id|name|email|...               │ col: user_pseudo_id    │ per query stage,
                                         │ col: event_params      │ returned after
index → find 1 row fast                  │ ...                    │
full scan = slow                       no indexes; prune by partition / cluster
you pay for the box, idle or not       pay per byte read  OR  per slot reserved

The consequence that matters day to day: cost is a function of bytes scanned, and bytes scanned is a function of which columns and which partitions you touch. WHERE on an ordinary column doesn’t reduce it; LIMIT doesn’t reduce it; SELECT * maximises it.


At a glance

DialectGoogleSQL, Google’s SQL (Structured Query Language) dialect (formerly “standard SQL”). Legacy SQL still exists; ignore it — SQL Dialects
HierarchyOrganisation → project → dataset → table / view
LocationSet per dataset at creation, can’t be changed. Region (europe-west2 = London) or multi-region (EU, US)
Storage formatColumnar (Capacitor), compressed
Compute unitThe slot — a virtual CPU
Query billing modelsOn-demand (bytes processed) or capacity (slot-hours, via Editions)
Storage billing modelsLogical (uncompressed bytes) or physical (compressed bytes), chosen per dataset
Cost leversColumns selected · partition pruning · cluster pruning
LIMIT cuts cost?No, on non-clustered tables
Nested dataSTRUCT and ARRAY columns; UNNEST to flatten
GA4 (Google Analytics 4) exportDate-sharded tables events_YYYYMMDD, not partitioned
KeysPrimary/foreign keys can be declared, not enforced
Free useA monthly free tier, plus a no-card sandbox with expiring tables

The resource hierarchy

Organisation (your Google Workspace / Cloud Identity domain)
└─ Folder (optional)
   └─ Project ── billing account attached here
      │          jobs (queries, loads) run and bill HERE
      └─ Dataset ── location fixed at creation (EU, europe-west2…)
         │          storage billing model set here
         │          default table expiry set here
         ├─ Table             native, columnar
         ├─ View              saved query, no storage
         ├─ Materialised view precomputed, auto-refreshed
         ├─ External table    data stays in Cloud Storage / Drive
         └─ Routine           UDF or stored procedure

A routine is a UDF (user-defined function) or stored procedure. Fully-qualified name: `project.dataset.table` — backticks, because project IDs contain hyphens.

SELECT event_name
FROM `acme-analytics.analytics_123456789.events_20261028`
--    project        dataset              table

Billing project vs data project

The project that runs the job pays for the query; the project that holds the table pays for storage. They needn’t be the same.

acme-analytics (data project)        acme-bi (billing project)
  analytics_123456789/                 your query job runs here
    events_*        ← storage billed     ← bytes scanned billed
                      here                 here
  • To query you need bigquery.jobs.create in the project where the job runs, plus read on the dataset. Two separate grants, frequently confused — see
  • Common pattern: one data project holding raw exports, one project per team for running queries, so spend is attributable
  • Data Studio, dbt and notebooks each pick a billing project — check which one, or spend lands somewhere unexpected [CHECK: whether a Data Studio BigQuery data source bills the owner’s or the viewer’s project depends on its credential setting]

Location

  • A region is one place (europe-west2, London). A multi-region is a large area (EU, US); EU data is stored in Belgium or the Netherlands, chosen by BigQuery — not London
  • Location is fixed at dataset creation. Moving means recreating and copying
  • A query runs in one location; tables from datasets in different locations can’t normally be joined in one query [CHECK: cross-region/global query support has been changing — verify before designing around it]
  • UK data-residency questions start here — Data Residency, UK GDPR and PECR for Analytics

Storage

Storage and compute, separated

           ┌──────────────── COMPUTE ────────────────┐
query ──→  │  stage 1: scan/filter   [slot][slot][slot]...
           │        │ shuffle (in-memory, network)
           │  stage 2: aggregate     [slot][slot]...
           │        │
           │  stage 3: sort/output   [slot]
           └────────│────────────────────────────────┘
                    │ petabit network
           ┌────────▼─────────── STORAGE ───────────────┐
           │  table → partitions → blocks → columns      │
           │  Capacitor columnar files, compressed       │
           │  2 copies, 2 zones within the region        │
           └─────────────────────────────────────────────┘

Two consequences:

  • Storage costs nothing to query and compute costs nothing to keep. A 10 TB table nobody touches is a storage bill only. A busy dashboard on a 1 GB table is a compute bill only
  • Scaling is not your problem. No vacuum, no rebalancing, no “the warehouse is full”

Columnar, and why SELECT * hurts

Columnar storage keeps each column’s values together rather than each row’s — Query Performance. A query reads only the columns it names, so a 3-column query on a 60-column table reads 3 columns’ worth of bytes.

ROW STORE (Postgres)                   COLUMN STORE (BigQuery)
[u1|page_view|10:00|{...params}]       event_name:   page_view, add_to_cart, page_view...
[u1|add_to_cart|10:12|{...}]           user_pseudo_id: u1, u1, u2...
[u2|page_view|10:13|{...}]             event_params: {...}, {...}, {...}

SELECT event_name → reads every row    SELECT event_name → reads ONE column

Compression is also far better — a column of event_name holds a few dozen distinct values repeated millions of times.

Partitioning

A partitioned table is one table physically divided into segments by a column’s value, so a filter on that column skips whole segments before reading anything — partition pruning.

Partition typeOnGranularity
Time-unit columnA DATE, TIMESTAMP or DATETIME columnHourly, daily (default), monthly, yearly. DATE can’t be hourly
Ingestion timeWhen the row was loaded — pseudocolumn _PARTITIONTIME / _PARTITIONDATESame
Integer rangeAn INT64 column, with start/end/intervalFixed buckets
CREATE TABLE `acme-bi.marts.events`
PARTITION BY event_date            -- a DATE column
CLUSTER BY event_name, user_pseudo_id
OPTIONS (require_partition_filter = TRUE)   -- refuse queries with no date filter
AS SELECT ...;
  • Partition boundaries are UTC (Coordinated Universal Time) for timestamp columns — a London-midnight boundary isn’t a partition boundary unless you partition on a DATE computed in London time — Timezones and Date Boundaries
  • Limits: 10,000 partitions per table; 4,000 partitions modified by one job. Daily partitions for 27 years fit; hourly for 14 months don’t
  • Pruning needs a filter BigQuery can evaluate before running — a constant or a simple expression on the partition column. Wrapping the column in a function, or filtering via a subquery result, can lose the pruning [CHECK: exact rules on which expressions prune]
  • require_partition_filter is the cheapest guardrail there is — a query with no date filter fails instead of scanning years

Clustering

A clustered table keeps rows sorted by up to four columns within each partition, so blocks whose value range can’t match a filter are skipped — block pruning.

PARTITION 2026-10-28, CLUSTER BY event_name

block 1: add_to_cart … begin_checkout
block 2: page_view   … page_view        ← WHERE event_name = 'purchase'
block 3: purchase    … scroll           ← only this block is read
block 4: session_start … view_item
PartitioningClustering
ColumnsOneUp to four, order matters
Cost known before running?Yes — dry run is accurateNo — the estimate is an upper bound
Good forDate rangesHigh-cardinality filters: user_id, event_name, SKU (stock keeping unit)
MaintenanceNoneAutomatic reclustering, free
LIMIT stops early?NoCan

Partition by date, cluster by what you filter on next. That’s nearly always the right shape for event data — Cardinality.

Storage billing

Two independent axes:

Active vs long-term — a table or partition not modified for 90 consecutive days drops automatically to the long-term rate (roughly half). No performance difference. Each partition ages separately, so old days of an events table are cheap and today’s isn’t.

Logical vs physical — set per dataset:

LOGICAL (default)                      PHYSICAL
billed on uncompressed bytes           billed on compressed bytes on disk
time travel + fail-safe: free          time travel + fail-safe: BILLED
                                       (at active rate)
good when: data churns a lot           good when: data compresses well
  (lots of updates/deletes             and isn't rewritten often —
   inflate time travel)                typical event data

Switching is a metering change, not a migration; you then have to wait 14 days to switch back. Compare both in INFORMATION_SCHEMA.TABLE_STORAGE before deciding [CHECK: exact view and column names for the logical-vs-physical comparison].

Time travel and fail-safe

  • Time travel — query or restore a table as it was at any point in the window. Default 7 days, configurable 2–7 per dataset
  • Fail-safe — a further 7 days after that, not configurable, recoverable only via Google support
SELECT * FROM `acme-bi.marts.orders`
  FOR SYSTEM_TIME AS OF TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 1 HOUR);
-- the table an hour ago: the "I just ran DELETE without WHERE" undo

Table types

TypeData livesNotes
Native tableBigQuery storageThe default. Everything above applies
ViewNowhere — it’s a saved queryQuerying it bills the underlying scan every time
Materialised viewBigQuery storage, precomputedSee below
External tableCloud Storage, Google Drive (incl. Sheets), BigtableNo caching, slower, cost estimates unreliable. Good for “join this sheet once”
BigLake tableObject storage (Cloud Storage, S3, Azure), often IcebergExternal data with BigQuery’s fine-grained security and metadata caching on top
Snapshot / cloneStores only the delta from the baseCheap point-in-time copies
Sharded tablesMany tables, name_YYYYMMDDNot a table type — a naming convention. What GA4 uses. Google recommends partitioning instead

Sharding vs partitioning matters because the GA4 export is sharded. Each shard is a separate table with its own schema and permissions check, which adds overhead; wildcard queries over shards also never hit the cache. Most teams query GA4 raw only to build a partitioned copy — .


Query execution and pricing

Slots

A slot is BigQuery’s unit of compute — a virtual CPU. A query is compiled into stages; each stage asks for as many slots as it can use, work units queue when slots run out, and waiting isn’t billed.

  • You can’t set how many slots a query uses
  • On-demand projects share a pool: up to 2,000 concurrent slots per project, 20,000 per organisation, with short bursts above
  • Under capacity pricing, slots come from reservations you configure

The two query billing models

Billing axes only. Figures change and vary by region.

ON-DEMAND                                  CAPACITY (Editions)
─────────                                  ───────────────────
billed per byte PROCESSED                  billed per SLOT-HOUR
  · rounded up to the nearest MB             · Standard / Enterprise /
  · minimum 10 MB per table referenced         Enterprise Plus
  · minimum 10 MB per query                  · baseline slots: always on,
  · first chunk each month free                always billed
slots: shared pool, up to 2,000/project    · autoscaled slots: added in
                                               multiples of 50, billed per
cost ∝ data read                               second, 1-minute minimum
cheap query = few columns, few partitions  · commitments (1 / 3 yr) discount
                                               the baseline
                                           cost ∝ compute time
                                           cheap query = fast query
  • Projects with no reservation assignment default to on-demand. Reservations are assigned to projects, folders or the whole organisation
  • On-demand is right for most ecommerce analytics — usage is bursty and small. Capacity pays off when on-demand bytes are consistently large, or when cost must be predictable
  • The incentives differ: under on-demand, a CPU-heavy query over a small table is nearly free; under capacity, a query that scans a lot but quickly is cheap
  • Editions also gate features (security, BI Engine size, etc.) [CHECK: which features sit in which edition — changes often]

What’s free, and what isn’t

  • Free: batch loading, copying tables, exporting, automatic reclustering, deleting, cached results, metadata-only operations
  • Billed: queries (either model), storage, streaming ingestion (the Storage Write API — application programming interface), BI Engine (business intelligence) capacity, cross-region replication
  • Cancelling a query doesn’t guarantee no charge — it can bill up to the full cost
  • Query results cache: identical query, unchanged tables → served free, typically for 24 hours, best-effort. Not used when the query uses CURRENT_DATE()/CURRENT_TIMESTAMP(), a wildcard table, a destination table, or a table with recent streaming writes. That list rules out caching for almost every naïve GA4 query

What makes a query expensive

Under on-demand, the bill is bytes processed = sum over columns referenced of (that column’s size in the partitions/blocks read). Logical sizes: INT64/FLOAT64/TIMESTAMP 8 bytes; BOOL 1; STRING 2 bytes + its UTF-8 (the standard Unicode byte encoding) length; STRUCT/ARRAY the sum of their contents.

Does it reduce bytes scanned?
Naming fewer columnsYes — the biggest lever
Filter on the partition column / _TABLE_SUFFIXYes
Filter on a clustering columnYes, but not known in advance
WHERE on any other columnNo — the column is read to evaluate the filter
LIMITNo (except sometimes on clustered tables)
SELECT * EXCEPT(event_params)Yes — the useful form of *
Table preview in the consoleFree — use it instead of SELECT * LIMIT 10

Worked example — one GA4 property, three versions of the same question

Setup (illustrative numbers, shape realistic): a mid-sized store sending 500,000 events/day, 13 months of GA4 export = 395 daily tables.

rows in scope, all history   = 500,000 × 395       = 197,500,000 rows

approx logical bytes per row, by column:
  event_name       ~12 chars + 2      =    14 B
  user_pseudo_id   ~20 chars + 2      =    22 B
  event_timestamp  INT64              =     8 B
  event_params     repeated structs   = ~1,500 B   ← the fat one
  everything else  device, geo, items… = ~1,000 B
  ───────────────────────────────────────────────
  full row                            ≈ 2,544 B

Q1 — SELECT * over all tables

197,500,000 rows × 2,544 B = 502,440,000,000 B ≈ 502 GB   (≈ 0.46 TiB)

Q2 — name three columns, still all history

columns: event_name + user_pseudo_id + event_timestamp
         = 14 + 22 + 8 = 44 B per row
197,500,000 × 44 B = 8,690,000,000 B ≈ 8.7 GB

58× cheaper. But the moment the query needs any parameter — page_location, transaction_id, an experiment variant — event_params comes in whole:

44 + 1,500 = 1,544 B per row
197,500,000 × 1,544 B ≈ 305 GB

Unnesting one key still reads the entire event_params column. On GA4 data, column selection saves less than you’d expect, because the column you nearly always need is the biggest one.

Q3 — same columns plus event_params, restricted to a 28-day test window via _TABLE_SUFFIX

rows = 500,000 × 28 = 14,000,000
14,000,000 × 1,544 B = 21,616,000,000 B ≈ 21.6 GB
Q1  SELECT *, all history           ≈ 502   GB
Q2  3 cols + params, all history    ≈ 305   GB
Q3  3 cols + params, 28 days        ≈  21.6 GB   ← 23× less than Q1

What to notice: the date restriction did more than the column restriction, because GA4’s fat column is unavoidable. Then a dashboard re-running Q3 every time someone opens it — wildcard query, so no cache — multiplies it by every view. That’s the argument for building a narrow, partitioned table once and pointing everything at that.

Guardrails

  • Dry run — the console’s query validator shows estimated bytes before you run. Accurate for partitioned tables, an upper bound for clustered ones
  • Maximum bytes billed — set per query (or as a default); if the estimate exceeds it, the query fails without charge
  • Custom quotas — cap on-demand bytes per project per day (default 200 TiB/day — high enough to be no guardrail at all) or per user
  • INFORMATION_SCHEMA.JOBS — every job’s bytes billed, user and query text. Who’s spending is one query away:
SELECT user_email,
       SUM(total_bytes_billed) / POW(1024, 4) AS tib_billed,
       COUNT(*) AS jobs
FROM `region-eu`.INFORMATION_SCHEMA.JOBS      -- region qualifier required
WHERE creation_time >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 30 DAY)
  AND job_type = 'QUERY'
GROUP BY user_email
ORDER BY tib_billed DESC;

Limits worth knowing

LimitValue
Query execution time6 hours (retries can extend wall time)
Partitions per table10,000
Partitions modified per job4,000
Clustering columns4
Max response size10 GB compressed — unlimited if written to a destination table
Max row size100 MB
On-demand concurrent slots2,000 per project · 20,000 per organisation
On-demand bytes per project per day (default custom quota)200 TiB
Time travel2–7 days, default 7 · fail-safe 7 more

GoogleSQL quirks

Standard SQL with three big additions (nested data, wildcards, SAFE.) and the usual dialect differences in SQL Dialects. Window functions and CTEs (common table expressions — WITH blocks) work as everywhere — Window Functions, Common Table Expressions.

Nested and repeated fields

A STRUCT is a column holding named sub-fields — a row inside a cell. An ARRAY is a column holding an ordered list of same-typed values. A repeated record is an ARRAY<STRUCT<…>> — a little table inside one cell. BigQuery’s schema calls them RECORD and mode REPEATED.

SELECT
  STRUCT('Chrome' AS browser, 'desktop' AS category) AS device,  -- STRUCT
  ['page_view', 'scroll']                            AS events,  -- ARRAY<STRING>
  [STRUCT('sku_1' AS item_id, 2 AS qty),
   STRUCT('sku_2' AS item_id, 1 AS qty)]             AS items;   -- ARRAY<STRUCT>
-- one row back
  • Struct fields: dot access — device.category, geo.country
  • Array elements: no dot access — you UNNEST, which turns an array into rows

Why nest at all: denormalisation without the join. An event and its parameters are stored together, so there’s no event_params table to join and no fan-out until you ask for one — Normalisation.

UNNEST — two shapes

1. As a correlated subquery — pull one value out, row count unchanged:

SELECT
  event_name,
  (SELECT value.string_value
     FROM UNNEST(event_params)
     WHERE key = 'page_location') AS page_location   -- scalar: one value per event
FROM `acme-analytics.analytics_123456789.events_20261028`;

2. As a join — one output row per array element. This fans out:

SELECT event_name, item.item_id, item.quantity
FROM `acme-analytics.analytics_123456789.events_20261028`,
     UNNEST(items) AS item            -- comma = CROSS JOIN; events with empty items DISAPPEAR
WHERE event_name = 'purchase';
  • Comma/CROSS JOIN UNNEST drops rows whose array is empty. Use LEFT JOIN UNNEST(items) AS item to keep them
  • Never UNNEST two independent arrays in one FROM — event_params × items is a Cartesian product per row. Summing revenue after that is the classic double count — Double Counting, Joins

Wildcard tables and _TABLE_SUFFIX

A wildcard table queries every table matching a prefix as one; _TABLE_SUFFIX is a pseudocolumn holding the part the * matched.

FROM `acme-analytics.analytics_123456789.events_*`
WHERE _TABLE_SUFFIX BETWEEN '20261001' AND '20261028'   -- string comparison
  • Only constant filters on _TABLE_SUFFIX prune tables. A suffix computed from a subquery scans every matching table
  • events_* also matches events_intraday_20261029 — its suffix is intraday_20261029. BETWEEN '2026…' excludes it by luck of string ordering ('i' > '2'); a looser filter (>= '20261001') includes it. Use events_2* or be explicit
  • Schema comes from the most recently created matching table; a column added since is NULL in older ones; a type conflict errors
  • Never cached

SAFE. prefix

Prefix almost any scalar function with SAFE. and it returns NULL instead of erroring on a bad input value:

SELECT
  SAFE_CAST('£12.50' AS NUMERIC),          -- NULL instead of query failure
  SAFE_DIVIDE(conversions, sessions),      -- NULL when sessions = 0
  SAFE.PARSE_DATE('%Y%m%d', event_date);   -- NULL on a malformed date

SAFE_CAST and SAFE_DIVIDE are named functions doing the same job; SAFE. is the general prefix.

It only guards the prefixed function itself, not errors in its arguments. The trap: it hides bad data as NULL, and NULLs drop silently from AVG, COUNT(col) and WHERE. Count the NULLs once.

QUALIFY

Filters on a window function’s result without a wrapping subquery — the GoogleSQL answer to “keep the first row per user”:

SELECT user_pseudo_id, event_timestamp, variant
FROM exposures
QUALIFY ROW_NUMBER() OVER (PARTITION BY user_pseudo_id ORDER BY event_timestamp) = 1;

Window Functions for the window itself.

Other differences that bite

  • Integer division: / always returns FLOAT64; DIV(a, b) for integer
  • String comparison is case-sensitive — 'Email' != 'email', so channel grouping fragments by UTM (urchin tracking module) value — UTM Governance
  • TIMESTAMP is an instant (UTC); DATETIME is wall-clock with no zone. GA4’s event_timestamp is neither — it’s INT64 microseconds: TIMESTAMP_MICROS(event_timestamp)
  • COUNT(DISTINCT x) is exact; APPROX_COUNT_DISTINCT(x) uses HyperLogLog++ and is cheaper — which is also what GA4’s own UI (user interface) does, and one reason its user counts differ from yours — User Counting

The GA4 export

The reason most web and CRO (conversion rate optimisation) people meet BigQuery at all. GA4, usually fed by gtag or GTM (Google Tag Manager — Google Tag Manager), can export raw, unsampled, event-level data into a BigQuery project you own — the only route to row-level GA4 data, and the escape from the UI’s sampling, thresholding and fixed attribution — Warehouse-First Analytics, Data Sampling.

The pipeline

browser / app
  gtag / GTM  ──→  GA4 collection
                      │
                      ├──→ GA4 processing → reports / UI
                      │      (modelling, Google signals, thresholding,
                      │       attribution, HyperLogLog++ estimates)
                      │
                      └──→ BigQuery export (raw events, none of the above)
                             │
              ┌──────────────┼──────────────────────────┐
              │              │                          │
         STREAMING        DAILY                 FRESH DAILY (360 only)
         continuous       once a day, previous   daily, complete,
              │           day, ~early afternoon   faster
              ▼           (property timezone)
    events_intraday_YYYYMMDD     events_YYYYMMDD
    (staging; deleted once       (the stable one; updated with
     the daily table lands)       late events for up to 72 hours)

dataset: analytics_<property_id>
optional user-data export: pseudonymous_users_YYYYMMDD, users_YYYYMMDD
DailyStreamingFresh daily
Tablesevents_YYYYMMDDevents_intraday_YYYYMMDD[CHECK: table name]
AvailabilityAll propertiesAll properties, not the sandboxAnalytics 360 only
Volume limit1 million events/day on standard propertiesNone[CHECK: 360 limits]
CostNo GA4 charge; BigQuery storage/queryBilled as BigQuery streaming ingestion (per data volume)—
CompletenessFull schema, late events added for 72 hMissing first-touch traffic_source for new users, user_ltv, is_active_userFull

The 1 million cap is the one that bites growing stores. Consistently exceeding it pauses the daily export, and paused days aren’t reprocessed. Fixes: exclude noisy events or streams from the export (configurable at link time or later), use streaming, or 360.

Other set-up facts:

  • Region is chosen at link time and effectively permanent — changing it means unlinking, recreating the dataset and relinking, with a gap. Choose EU or europe-west2 deliberately
  • A valid billing method is required for exports to continue; an export interrupted for billing reasons isn’t backfilled
  • No backfill at all, ever. Export starts the day you link. Link on day one even if no one queries it for a year — storage of old shards drifts to long-term pricing on its own
  • The sandbox takes the daily export free, but its tables expire after 60 days and it has no streaming. Fine for learning the schema; not an archive

The schema

One row per event. Fields worth knowing, grouped:

event_date              STRING  'YYYYMMDD', PROPERTY timezone
event_timestamp         INT64   microseconds, UTC
event_name              STRING
event_params            ARRAY<STRUCT<key STRING,
                                     value STRUCT<string_value STRING,
                                                  int_value    INT64,
                                                  float_value  FLOAT64,  -- unused
                                                  double_value FLOAT64>>>
user_pseudo_id          STRING  the cookie / app-instance ID
user_id                 STRING  only if you set User-ID
user_properties         ARRAY<STRUCT<key, value{…, set_timestamp_micros}>>
user_first_touch_timestamp, user_ltv{revenue, currency}
privacy_info            {analytics_storage, ads_storage, uses_transient_token}
device                  {category, operating_system, web_info{browser, hostname}…}
geo                     {country, region, city…}  — from the IP address
traffic_source          {name, medium, source}  — FIRST touch of the user, never changes
collected_traffic_source {manual_source, manual_medium, manual_campaign_name…, gclid}
session_traffic_source_last_click {manual_campaign{…}, google_ads_campaign{…}, …}
ecommerce               {transaction_id, purchase_revenue, total_item_quantity…}
items                   ARRAY<STRUCT<item_id, item_name, item_variant, price,
                                     quantity, item_revenue, item_params[…]>>
stream_id, platform, batch_event_index, batch_page_id, batch_ordering_id

Things that catch people:

  • traffic_source is the user’s first acquisition source, not the session’s. Session source is session_traffic_source_last_click; per-event UTM and GCLID (Google click identifier) values are in collected_traffic_source — Attribution Models
  • Each parameter value lands in exactly one of string_value / int_value / double_value, based on its type when sent. A parameter sent as a number on one page and a string on another lands in different fields; COALESCE across them or you lose rows
  • ga_session_id is a parameter, not a column. A session is user_pseudo_id + ga_session_id — the ID alone isn’t unique across users — Sessionisation
  • event_date is in the property’s timezone and event_timestamp in UTC — the shard boundary and the timestamp disagree for an hour in UK summer — Timezones and Date Boundaries
  • items is per-event, so item_revenue lives on the purchase event’s items; purchase_revenue on ecommerce. Summing both double counts
  • The ID you sent as item_id is what you get — variant or product is decided in the data layer, not here — Ecommerce Event Schema

A raw row, and flattening it

One row as stored (a purchase):

event_date  event_name  user_pseudo_id   event_params                              items
20261028    purchase    1834.1730091     [{key: ga_session_id,                     [{item_id: SKU-236,
                                            value: {int_value: 1730091200}},          quantity: 1,
                                          {key: page_location,                        price: 9.99},
                                            value: {string_value: '/checkout/…'}},   {item_id: SKU-473,
                                          {key: transaction_id,                       quantity: 2,
                                            value: {string_value: 'T-90211'}}]        price: 14.99}]

One row, three parameters, two items. Now the two UNNEST patterns:

SELECT
  PARSE_DATE('%Y%m%d', event_date)                                         AS event_date,
  user_pseudo_id,
  (SELECT value.int_value    FROM UNNEST(event_params) WHERE key = 'ga_session_id')  AS ga_session_id,
  (SELECT value.string_value FROM UNNEST(event_params) WHERE key = 'transaction_id') AS transaction_id,
  item.item_id,
  item.quantity,
  item.price * item.quantity                                               AS line_revenue
FROM `acme-analytics.analytics_123456789.events_*`,
     UNNEST(items) AS item                         -- fan out: one row per item
WHERE _TABLE_SUFFIX = '20261028'
  AND event_name = 'purchase';

After:

event_date  user_pseudo_id  ga_session_id  transaction_id  item_id  quantity  line_revenue
2026-10-28  1834.1730091    1730091200     T-90211         SKU-236  1          9.99
2026-10-28  1834.1730091    1730091200     T-90211         SKU-473  2         29.98   ← same order, 2nd row

What to notice: the parameters were pulled sideways into columns with scalar subqueries (row count unchanged), and the items were fanned out with a join (row count ×2). Any order-level figure — ecommerce.purchase_revenue, order count — is now duplicated per item. Count orders with COUNT(DISTINCT transaction_id), never COUNT(*).

Why the export doesn’t match the UI

Expect a gap, and know the causes before investigating — Tool Discrepancies:

  • No modelled data. Consent-mode modelling fills gaps in the UI; none of it reaches the export
  • Cookieless pings (consent denied, Advanced consent mode) do reach the export — each session with a different user_pseudo_id, so user counts from the export run high. Filter on privacy_info.analytics_storage — Consent Management
  • HyperLogLog++ in the UI — UI users and sessions are estimates; your COUNT(DISTINCT) is exact
  • Google signals / reporting identity merge devices in the UI; the export keeps separate IDs — Cross-Device Tracking
  • Thresholding withholds rows in UI reports
  • Attribution — the UI applies its own session attribution model; the export gives you raw sources to model yourself
  • Late events — daily tables change for 72 hours; compare data older than that
  • Export filters and the 1M cap — excluded events simply aren’t there

Experiment analysis on the export

GA4 has no experiment object. The testing tool (or your own code) sends an exposure event with the experiment and variant as parameters, and the analysis is: first exposure per user → outcomes after that exposure → aggregate by variant — Experiment Assignment Tracking.

Assume the data layer sends experiment_exposure with experiment_id and variant_id (names are whatever your implementation chose).

Built up, one rung at a time:

Rung 1 — the smallest complete query. Exposure events for one test, one day. Runs as-is.

SELECT user_pseudo_id, event_timestamp
FROM `acme-analytics.analytics_123456789.events_20261028`
WHERE event_name = 'experiment_exposure';

Rung 2 — the test window, via wildcard:

SELECT user_pseudo_id, event_timestamp
FROM `acme-analytics.analytics_123456789.events_*`
WHERE _TABLE_SUFFIX BETWEEN '20261001' AND '20261028'
  AND event_name = 'experiment_exposure';

Rung 3 — pull the parameters out:

SELECT
  user_pseudo_id,
  event_timestamp,
  (SELECT value.string_value FROM UNNEST(event_params) WHERE key = 'experiment_id') AS experiment_id,
  (SELECT value.string_value FROM UNNEST(event_params) WHERE key = 'variant_id')    AS variant_id
FROM `acme-analytics.analytics_123456789.events_*`
WHERE _TABLE_SUFFIX BETWEEN '20261001' AND '20261028'
  AND event_name = 'experiment_exposure';

Rung 4 — first exposure per user, via QUALIFY:

-- ...rung 3's SELECT/FROM/WHERE, then:
QUALIFY ROW_NUMBER() OVER (PARTITION BY user_pseudo_id ORDER BY event_timestamp) = 1
Does the analysis need…
A date filter on _TABLE_SUFFIXYes — cost and correctness (test window)
UNNEST(event_params)Yes — variant lives in a parameter
First-exposure dedupYes — users fire exposure on every page view
Excluding users seen in both variantsYes — or the arms contaminate — Sample Pollution
Outcomes after exposure onlyYes — a purchase before exposure isn’t an effect
Filtering cookieless pingsYes — they can’t be joined across sessions
user_id instead of user_pseudo_idOptional — only if randomisation was by logged-in user — Randomisation Unit
Revenue per userOptional — conversion alone is the minimum

The kitchen-sink version — the whole analysis as one query, top to bottom:

DECLARE exp STRING DEFAULT 'pdp-sticky-atc-03';
 
WITH exposures AS (
  SELECT
    user_pseudo_id,
    event_timestamp AS exposed_at,
    (SELECT value.string_value FROM UNNEST(event_params) WHERE key = 'variant_id') AS variant
  FROM `acme-analytics.analytics_123456789.events_*`
  WHERE _TABLE_SUFFIX BETWEEN '20261001' AND '20261028'   -- constant → prunes shards
    AND event_name = 'experiment_exposure'
    AND IFNULL(privacy_info.analytics_storage, '') != 'No' -- drop cookieless pings;
                                                            -- keep NULL (no consent mode)
    AND (SELECT value.string_value FROM UNNEST(event_params) WHERE key = 'experiment_id') = exp
),
 
clean_users AS (                       -- one variant per user, or out
  SELECT user_pseudo_id
  FROM exposures
  GROUP BY user_pseudo_id
  HAVING COUNT(DISTINCT variant) = 1
),
 
first_exposure AS (
  SELECT e.*
  FROM exposures e
  JOIN clean_users USING (user_pseudo_id)
  QUALIFY ROW_NUMBER() OVER (PARTITION BY user_pseudo_id ORDER BY exposed_at) = 1
),
 
purchases AS (
  SELECT
    user_pseudo_id,
    event_timestamp AS purchased_at,
    ecommerce.transaction_id,
    ecommerce.purchase_revenue
  FROM `acme-analytics.analytics_123456789.events_*`
  WHERE _TABLE_SUFFIX BETWEEN '20261001' AND '20261031'  -- +3 days: late conversions
    AND event_name = 'purchase'
)
 
SELECT
  f.variant,
  COUNT(DISTINCT f.user_pseudo_id)                                  AS users,
  COUNT(DISTINCT IF(p.purchased_at > f.exposed_at, f.user_pseudo_id, NULL)) AS converters,
  SAFE_DIVIDE(
    COUNT(DISTINCT IF(p.purchased_at > f.exposed_at, f.user_pseudo_id, NULL)),
    COUNT(DISTINCT f.user_pseudo_id))                               AS conversion_rate,
  SUM(IF(p.purchased_at > f.exposed_at, p.purchase_revenue, 0))     AS revenue
FROM first_exposure f
LEFT JOIN purchases p USING (user_pseudo_id)   -- LEFT: keep non-converters
GROUP BY f.variant
ORDER BY f.variant;

The trick lines: the HAVING COUNT(DISTINCT variant) = 1 exclusion, QUALIFY for first exposure, and purchased_at > exposed_at so only post-exposure purchases count. Revenue is summed per purchase row — fine, because purchases has one row per purchase event and no items unnest. Deduplicate on transaction_id first if your site double-fires purchase — Idempotency and Deduplication.

Output (illustrative):

variant   users    converters  conversion_rate  revenue
control   24,806   868         0.0350           £41,120
variant   25,194   957         0.0380           £45,880

Read it in two steps.

1. Check the split first — the sample ratio mismatch (SRM) check. SRM is when the observed split between arms differs from the designed split by more than chance allows — a sign that assignment or tracking is broken — Sample Ratio Mismatch. Designed 50/50, so expected 25,000 each.

total            = 24,806 + 25,194      = 50,000
expected per arm = 50,000 × 0.5         = 25,000
deviation        = 25,194 − 25,000      = 194      (and −194 for control)

chi-square = Σ (observed − expected)² / expected
           = 194² / 25,000  +  194² / 25,000
           = 37,636 / 25,000 × 2
           = 1.505 × 2
           = 3.01
1 degree of freedom → p ≈ 0.08

The chi-square statistic sums each arm’s squared surprise relative to what was expected. One degree of freedom because with two arms and a fixed total, once one count is known the other is too. The p-value is the probability of a split at least this uneven if assignment were working perfectly — P-Values, Other Statistical Tests.

In plain terms: a split this uneven would happen about 8 times in 100 by chance alone with a perfectly working 50/50 split — not suspicious. SRM checks usually alarm only at much smaller probabilities (≈ 0.001), because they’re run on every test and a false alarm halts analysis.

2. Then the effect:

control rate  = 868 / 24,806 = 0.03499 ≈ 3.50%
variant rate  = 957 / 25,194 = 0.03798 ≈ 3.80%
absolute diff = 3.80 − 3.50  = 0.30 percentage points
relative lift = 0.03798 / 0.03499 − 1 = 0.0855 ≈ +8.5%

Whether +8.5% is distinguishable from noise is a Proportion Tests question, and whether the test was big enough to trust it is Statistical Power. BigQuery produces the counts; the inference happens after. Revenue per user is a Ratio Metrics problem with a heavy-tailed numerator — Skewed and Heavy-Tailed Distributions, Winsorisation and Capping.

Why do this in BigQuery instead of the testing tool’s dashboard: you control the exposure definition, can cut by segment after the fact (carefully — Segmentation (test results)), can join to refunds, margin or CRM (customer relationship management) data the tool never saw, and can reproduce the number six months later — Post-Test Validation.


Building on top

Modelling the export

The raw GA4 tables are the wrong thing to point dashboards and analysts at: sharded, nested, every query re-scanning event_params. Standard shape, ending in reverse ETL (extract, transform, load run backwards — warehouse out to tools) — Reverse ETL:

events_YYYYMMDD (raw, sharded, nested)
   │  daily job, last ~3 days reprocessed (late events)
   ▼
stg_events         partitioned by event_date, clustered by event_name,
                   key params flattened to columns, cookieless pings flagged
   ▼
sessions · purchases · experiment_exposures     (narrow marts)
   ▼
Data Studio / notebooks / reverse ETL (warehouse → tools)

Reprocessing the trailing three days is what handles the 72-hour late-event window — an incremental job that only processes “yesterday” silently under-counts.

Scheduled queries

A saved query run on a schedule, writing to a destination table. Runs on the BigQuery Data Transfer Service — so not available in the sandbox. Parameters @run_date and @run_time let a query process “the day this run is for”:

-- scheduled daily; destination: stg_events, partition: {run_date}
SELECT ...
FROM `acme-analytics.analytics_123456789.events_*`
WHERE _TABLE_SUFFIX = FORMAT_DATE('%Y%m%d', DATE_SUB(@run_date, INTERVAL 1 DAY))

Fine for two or three jobs. Past that, the dependencies, tests and version control want dbt.

dbt

dbt (data build tool) compiles SQL SELECT files into tables and views, in dependency order, with tests and documentation. On BigQuery it maps cleanly: a model is a table; partition_by and cluster_by are model config; incremental models can replace whole date partitions (the insert_overwrite strategy), which is exactly the reprocess-the-last-3-days pattern above. Community GA4 packages exist that do the flattening for you [CHECK: current maintained GA4 dbt package and its state].

Materialised views

A materialised view stores a query’s precomputed result and keeps it current automatically, reading only changed base data where it can (incremental refresh).

  • Queries against the base table can be rewritten to use the view automatically (smart tuning) — only for incremental views
  • Restricted SQL: limited aggregate functions, GoogleSQL only, no materialised view over another
  • max_staleness (30 minutes to 3 days) trades freshness for cost
  • Refresh is billed to the view’s project
  • Good fit: a daily aggregate that dashboards hit constantly. Poor fit: anything with complex joins or window functions — make a scheduled table instead

BI Engine

BI Engine is an in-memory acceleration layer: you reserve memory capacity, and it caches the most-used data so dashboard queries return in sub-second time.

  • Billing axis: reserved memory capacity over time, not bytes scanned [CHECK: how BI-Engine-served queries count against on-demand bytes]
  • Integrates with Looker, Data Studio, Tableau, Power BI and the API
  • Partition and cluster the underlying tables so the hot data fits in the reservation
  • Not every query shape accelerates; unsupported parts fall back to normal execution

Data Studio (Looker Studio 2022–26)

The native free dashboard tool, renamed back from Looker Studio in April 2026. Connects to BigQuery directly; every chart is a query, every filter change is another, and most of them miss the cache. A dashboard on raw GA4 shards with ten charts and twenty viewers is a few hundred full scans a day — the worked example above, multiplied. Point it at a small partitioned mart, use date-range parameters that map to the partition column, and consider BI Engine before capacity pricing — Dashboard Design.


Access control

IAM (Identity and Access Management) roles, granted at organisation, project, dataset, or table level:

RoleCan
roles/bigquery.dataViewerRead table data and metadata
roles/bigquery.dataEditor+ create, update, delete tables
roles/bigquery.dataOwner+ manage the dataset’s access
roles/bigquery.jobUserRun jobs (queries) in a project — no data access by itself
roles/bigquery.userRun jobs + create datasets in a project
roles/bigquery.adminEverything

The pair you actually need: jobUser on the billing project + dataViewer on the dataset. “Access denied” with a perfectly good data grant almost always means the job permission is missing — Authentication vs Authorisation.

Finer grain:

  • Authorised views — a view in one dataset allowed to read a dataset the user can’t, so the user sees the view’s columns only
  • Row-level security — row access policies filter rows per principal (e.g. a regional team sees its country only). Dry runs on these tables always report 0 bytes
  • Column-level security — policy tags on sensitive columns
  • Service accounts for scheduled jobs and tools, never personal credentials — Secrets Management
  • The export holds pseudonymous IDs, IP-derived geo and possibly user_id — personal data under UK GDPR. Dataset access and table expiry are part of that compliance, not separate from it — PII in Analytics, Data Retention, Pseudonymisation and Anonymisation

Free use

  • Free tier — a monthly allowance of on-demand query bytes and of storage, on any billing-enabled project, during and after a trial
  • Sandbox — no billing account needed. Limits:
    • Tables, views and partitions expire after 60 days
    • A 10 GiB lifetime storage cap, not refunded when you delete
    • No streaming, no DML, no Data Transfer Service (so no scheduled queries)
    • Free-tier query allowance applies
  • Good for learning the GA4 schema on a real property. Upgrade by attaching billing; then reset the dataset’s default table expiry or the old shards keep expiring

Where it hurts

  • The cost model is invisible until the invoice. Nothing in the console stops a junior analyst running SELECT * over three years of events daily. Set maximum bytes billed and custom quotas on day one
  • Sharded GA4 tables — no partition pruning, no caching, schema drift between shards. Everybody ends up building the partitioned copy; budget for it from the start
  • Nested data and fan-out — the wrong UNNEST silently multiplies revenue. Every new query on items deserves a row-count sanity check against COUNT(DISTINCT transaction_id)
  • Locations are permanent — the GA4 link’s region and every dataset’s location. A wrong choice is a migration
  • Not an application database. No enforced keys, single-row lookups are slow and billed at the 10 MB minimum, DML is quota’d. Don’t serve a website from it
  • Export ≠ UI. Reconciling the two eats days unless the causes above are written down before anyone asks