Request a demo

GA4 in BigQuery · Cost and performance

Materialize GA4 sessions into a partitioned daily table

Turn the GA4 export into a session table partitioned by date and clustered by source and medium, then refresh only the last three days every morning. Dashboards read a few partitions of a small table instead of re-scanning event_params on every refresh.

Runs on Google's public sample bigquery-public-data.ga4_obfuscated_sample_ecommerce · Scans 1.6 GiB, under $0.01 on-demand · Checked in November 2026

The query

-- One-time build over the full history. Replace the target with your own project and dataset.
CREATE TABLE IF NOT EXISTS `your-project.ga4_derived.sessions`
PARTITION BY session_date
CLUSTER BY source, medium
AS
WITH events AS (
  SELECT
    PARSE_DATE('%Y%m%d', event_date) AS event_day,
    user_pseudo_id,
    event_timestamp,
    event_name,
    (SELECT value.int_value    FROM UNNEST(event_params) WHERE key = 'ga_session_id')        AS ga_session_id,
    (SELECT value.int_value    FROM UNNEST(event_params) WHERE key = 'ga_session_number')    AS ga_session_number,
    (SELECT value.string_value FROM UNNEST(event_params) WHERE key = 'page_location')        AS page_location,
    (SELECT value.string_value FROM UNNEST(event_params) WHERE key = 'source')               AS source,
    (SELECT value.string_value FROM UNNEST(event_params) WHERE key = 'medium')               AS medium,
    (SELECT COALESCE(value.string_value, CAST(value.int_value AS STRING))
       FROM UNNEST(event_params) WHERE key = 'session_engaged')                              AS session_engaged,
    (SELECT value.int_value    FROM UNNEST(event_params) WHERE key = 'engagement_time_msec') AS engagement_time_msec,
    device.category                   AS device_category,
    geo.country                       AS country,
    ecommerce.purchase_revenue_in_usd AS purchase_revenue_usd
  FROM `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_*`
  WHERE _TABLE_SUFFIX BETWEEN '20201101' AND '20210131'
),
sessions AS (
  SELECT
    MIN(event_day)                         AS session_date,
    user_pseudo_id,
    ga_session_id,
    MAX(ga_session_number)                 AS ga_session_number,
    TIMESTAMP_MICROS(MIN(event_timestamp)) AS session_start,
    ARRAY_AGG(IF(event_name = 'page_view', page_location, NULL) IGNORE NULLS
              ORDER BY event_timestamp LIMIT 1)[SAFE_OFFSET(0)] AS landing_page,
    ARRAY_AGG(IF(source IS NULL, NULL, STRUCT(source, medium)) IGNORE NULLS
              ORDER BY event_timestamp LIMIT 1)[SAFE_OFFSET(0)] AS src,
    ANY_VALUE(device_category)             AS device_category,
    ANY_VALUE(country)                     AS country,
    IFNULL(LOGICAL_OR(session_engaged = '1'), FALSE) AS is_engaged,
    IFNULL(SUM(engagement_time_msec), 0)   AS engagement_time_msec,
    COUNT(*)                               AS events,
    COUNTIF(event_name = 'page_view')      AS page_views,
    COUNTIF(event_name = 'purchase')       AS purchases,
    IFNULL(SUM(IF(event_name = 'purchase', purchase_revenue_usd, NULL)), 0) AS revenue_usd
  FROM events
  GROUP BY user_pseudo_id, ga_session_id
)
SELECT
  * EXCEPT (src),
  COALESCE(src.source, '(direct)') AS source,
  COALESCE(src.medium, '(none)')   AS medium
FROM sessions;

How it works

Every recipe in this cookbook that needs sessions, landing pages, source and medium or engagement reads event_params, and that is the expensive part of the export. If five dashboards do it on every refresh, you pay for the same unnesting many times a day. The fix is to do it once: build one row per session, store it in a table partitioned by date, and point reports at that table.

The query creates that table from the whole sample. Each row is a session with its date, landing page, first source and medium, device, country, engaged flag, engagement time, page views, purchases and revenue. The build reads 1,720,486,646 bytes (1.60 GiB) once. The sample's 4,295,584 events contain 354,970 session_start events, so the result has roughly one row for every 12 events, and no nested columns.

Partitioning and clustering. PARTITION BY session_date lets a report for last week read seven partitions instead of the whole table (partitioned table). CLUSTER BY source, medium sorts the data inside each partition, so filters on those columns read fewer blocks (clustered table). Cluster by whatever your reports filter on most.

Incremental refresh. GA4 keeps adding late events to a daily table for up to 72 hours. A daily job should therefore rebuild the last three days, not append yesterday: delete those partitions and insert them again from the export (first variation). It reads one extra day before the window so that a session starting just before midnight is not cut in half, and keeps only sessions that start inside the window. Rebuilding whole partitions makes the job idempotent: a rerun gives the same result. On the sample, a five-table refresh window reads 68.8 MiB.

Scheduling. A BigQuery scheduled query can run the script daily; replace CURRENT_DATE() with the @run_date parameter that scheduled queries provide, so backfills of past dates work. In dbt, the same logic is an incremental model with the insert_overwrite strategy (second variation). A materialized view is the other way to precompute, but Google's documentation lists window functions, UDFs and non-deterministic functions such as CURRENT_DATE() as unsupported in incremental materialized views, so a scheduled rebuild is the simpler fit for this logic.

ColumnMeaning
session_dateDate of the session's first event, in the property's time zone. Partitioning column.
landing_pagepage_location of the first page view.
source / mediumFirst source and medium collected in the session, or (direct) / (none).
is_engagedAny event in the session had session_engaged = 1.
engagement_time_msecSum of engagement_time_msec across the session's events.
revenue_usdSum of ecommerce.purchase_revenue_in_usd on purchase events.

Notes and cost

  • bytesProcessed for this page is the dry run of the SELECT that feeds the table, since the CREATE TABLE target does not exist in the public project. Writing the result adds storage, not query cost.
  • Create the derived dataset in the same location as the export. The sample is in the US multi-region; a query cannot read from one location and write to another (error reference).
  • After the build, a month of sessions by source and medium reads only the partitions for that month and a few columns. Compare that with 585.6 MiB for the bounce rate query over one month of raw events.
  • Add a partition_expiration_days option only if old sessions can be dropped; GA4 cannot re-export history once the daily tables are gone.
  • For older exports where the daily tables are already in BigQuery, a one-time backfill over the full history is cheaper than querying that history repeatedly.

Variations

Daily incremental refresh (script or scheduled query)

Deletes and rebuilds the last three days in one transaction. In a scheduled query, use DATE_SUB(@run_date, INTERVAL 3 DAY) for start_day and @run_date in place of CURRENT_DATE().

DECLARE start_day DATE DEFAULT DATE_SUB(CURRENT_DATE(), INTERVAL 3 DAY);

BEGIN TRANSACTION;

DELETE FROM `your-project.ga4_derived.sessions`
WHERE session_date >= start_day;

INSERT INTO `your-project.ga4_derived.sessions`
WITH events AS (
  SELECT
    PARSE_DATE('%Y%m%d', event_date) AS event_day,
    user_pseudo_id,
    event_timestamp,
    event_name,
    (SELECT value.int_value    FROM UNNEST(event_params) WHERE key = 'ga_session_id')        AS ga_session_id,
    (SELECT value.int_value    FROM UNNEST(event_params) WHERE key = 'ga_session_number')    AS ga_session_number,
    (SELECT value.string_value FROM UNNEST(event_params) WHERE key = 'page_location')        AS page_location,
    (SELECT value.string_value FROM UNNEST(event_params) WHERE key = 'source')               AS source,
    (SELECT value.string_value FROM UNNEST(event_params) WHERE key = 'medium')               AS medium,
    (SELECT COALESCE(value.string_value, CAST(value.int_value AS STRING))
       FROM UNNEST(event_params) WHERE key = 'session_engaged')                              AS session_engaged,
    (SELECT value.int_value    FROM UNNEST(event_params) WHERE key = 'engagement_time_msec') AS engagement_time_msec,
    device.category                   AS device_category,
    geo.country                       AS country,
    ecommerce.purchase_revenue_in_usd AS purchase_revenue_usd
  FROM `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_*`
  WHERE _TABLE_SUFFIX BETWEEN FORMAT_DATE('%Y%m%d', DATE_SUB(start_day, INTERVAL 1 DAY))
                          AND FORMAT_DATE('%Y%m%d', CURRENT_DATE())
),
sessions AS (
  SELECT
    MIN(event_day)                         AS session_date,
    user_pseudo_id,
    ga_session_id,
    MAX(ga_session_number)                 AS ga_session_number,
    TIMESTAMP_MICROS(MIN(event_timestamp)) AS session_start,
    ARRAY_AGG(IF(event_name = 'page_view', page_location, NULL) IGNORE NULLS
              ORDER BY event_timestamp LIMIT 1)[SAFE_OFFSET(0)] AS landing_page,
    ARRAY_AGG(IF(source IS NULL, NULL, STRUCT(source, medium)) IGNORE NULLS
              ORDER BY event_timestamp LIMIT 1)[SAFE_OFFSET(0)] AS src,
    ANY_VALUE(device_category)             AS device_category,
    ANY_VALUE(country)                     AS country,
    IFNULL(LOGICAL_OR(session_engaged = '1'), FALSE) AS is_engaged,
    IFNULL(SUM(engagement_time_msec), 0)   AS engagement_time_msec,
    COUNT(*)                               AS events,
    COUNTIF(event_name = 'page_view')      AS page_views,
    COUNTIF(event_name = 'purchase')       AS purchases,
    IFNULL(SUM(IF(event_name = 'purchase', purchase_revenue_usd, NULL)), 0) AS revenue_usd
  FROM events
  GROUP BY user_pseudo_id, ga_session_id
)
SELECT
  * EXCEPT (src),
  COALESCE(src.source, '(direct)') AS source,
  COALESCE(src.medium, '(none)')   AS medium
FROM sessions
WHERE session_date >= start_day;

COMMIT TRANSACTION;

The same model in dbt

insert_overwrite replaces only the partitions present in the new result, so the last three days are rebuilt on every run and older partitions stay untouched.

{{ config(
    materialized = 'incremental',
    incremental_strategy = 'insert_overwrite',
    partition_by = {'field': 'session_date', 'data_type': 'date'},
    cluster_by = ['source', 'medium']
) }}

WITH events AS (
  SELECT
    PARSE_DATE('%Y%m%d', event_date) AS event_day,
    user_pseudo_id,
    event_timestamp,
    event_name,
    (SELECT value.int_value    FROM UNNEST(event_params) WHERE key = 'ga_session_id')        AS ga_session_id,
    (SELECT value.int_value    FROM UNNEST(event_params) WHERE key = 'ga_session_number')    AS ga_session_number,
    (SELECT value.string_value FROM UNNEST(event_params) WHERE key = 'page_location')        AS page_location,
    (SELECT value.string_value FROM UNNEST(event_params) WHERE key = 'source')               AS source,
    (SELECT value.string_value FROM UNNEST(event_params) WHERE key = 'medium')               AS medium,
    (SELECT COALESCE(value.string_value, CAST(value.int_value AS STRING))
       FROM UNNEST(event_params) WHERE key = 'session_engaged')                              AS session_engaged,
    (SELECT value.int_value    FROM UNNEST(event_params) WHERE key = 'engagement_time_msec') AS engagement_time_msec,
    device.category                   AS device_category,
    geo.country                       AS country,
    ecommerce.purchase_revenue_in_usd AS purchase_revenue_usd
  FROM `your-project.analytics_123456789.events_*`
  WHERE _TABLE_SUFFIX >= '20201101'
  {% if is_incremental() %}
    AND _TABLE_SUFFIX >= FORMAT_DATE('%Y%m%d', DATE_SUB(CURRENT_DATE(), INTERVAL 4 DAY))
  {% endif %}
),
sessions AS (
  SELECT
    MIN(event_day)                         AS session_date,
    user_pseudo_id,
    ga_session_id,
    MAX(ga_session_number)                 AS ga_session_number,
    TIMESTAMP_MICROS(MIN(event_timestamp)) AS session_start,
    ARRAY_AGG(IF(event_name = 'page_view', page_location, NULL) IGNORE NULLS
              ORDER BY event_timestamp LIMIT 1)[SAFE_OFFSET(0)] AS landing_page,
    ARRAY_AGG(IF(source IS NULL, NULL, STRUCT(source, medium)) IGNORE NULLS
              ORDER BY event_timestamp LIMIT 1)[SAFE_OFFSET(0)] AS src,
    ANY_VALUE(device_category)             AS device_category,
    ANY_VALUE(country)                     AS country,
    IFNULL(LOGICAL_OR(session_engaged = '1'), FALSE) AS is_engaged,
    IFNULL(SUM(engagement_time_msec), 0)   AS engagement_time_msec,
    COUNT(*)                               AS events,
    COUNTIF(event_name = 'page_view')      AS page_views,
    COUNTIF(event_name = 'purchase')       AS purchases,
    IFNULL(SUM(IF(event_name = 'purchase', purchase_revenue_usd, NULL)), 0) AS revenue_usd
  FROM events
  GROUP BY user_pseudo_id, ga_session_id
)
SELECT
  * EXCEPT (src),
  COALESCE(src.source, '(direct)') AS source,
  COALESCE(src.medium, '(none)')   AS medium
FROM sessions
{% if is_incremental() %}
WHERE session_date >= DATE_SUB(CURRENT_DATE(), INTERVAL 3 DAY)
{% endif %}

Report from the summary table

SELECT
  session_date,
  source,
  medium,
  COUNT(*)                                 AS sessions,
  ROUND(COUNTIF(is_engaged) / COUNT(*), 4) AS engagement_rate,
  ROUND(SUM(revenue_usd), 2)               AS revenue_usd
FROM `your-project.ga4_derived.sessions`
WHERE session_date BETWEEN '2020-12-01' AND '2020-12-31'
GROUP BY session_date, source, medium
ORDER BY session_date, sessions DESC;

FAQ

Should I copy the GA4 export into a partitioned table?

For anything you query often, yes. A session or daily summary table partitioned by date is much smaller than the raw events and lets reports prune by date and skip event_params.

How many days should a GA4 incremental job reprocess?

At least three. Google updates daily tables with late events for up to 72 hours after the date, so a job that only appends yesterday misses late data.

Can I use a materialized view on the GA4 export?

Materialized views limit the SQL they accept; Google's docs list window functions, UDFs and non-deterministic functions such as CURRENT_DATE() as unsupported in incremental views. A scheduled table rebuild avoids those limits.

All GA4 export queries · BigQuery cost queries · The GA4 sample dataset

Cut BigQuery spend without guessing

Masthead attributes compute and storage cost to every project, user, pipeline and table, finds unused and dead-end tables, and shows where editions or on-demand pricing is cheaper. Mnemonic cut its BigQuery compute cost by 20% within 24 hours of onboarding.