# Materialize GA4 sessions into a partitioned daily table | GA4 BigQuery Export | Masthead

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.

> For the index of this section of the site, see [llms.txt](https://mastheadata.com/llms.txt)

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](https://mastheadata.com/glossary/partitioned-table.md)). `CLUSTER BY source, medium` sorts the data inside each partition, so filters on those columns read fewer blocks ([clustered table](https://mastheadata.com/glossary/clustered-table.md)). 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](https://mastheadata.com/glossary/idempotent-pipeline.md): 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](https://mastheadata.com/glossary/dbt.md), the same logic is an incremental model with the `insert_overwrite` strategy (second variation). A [materialized view](https://mastheadata.com/bigquery/sql/create-materialized-view.md) 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.

| Column | Meaning |
| --- | --- |
| `session_date` | Date of the session's first event, in the property's time zone. Partitioning column. |
| `landing_page` | `page_location` of the first page view. |
| `source / medium` | First source and medium collected in the session, or `(direct)` / `(none)`. |
| `is_engaged` | Any event in the session had `session_engaged` = 1. |
| `engagement_time_msec` | Sum of `engagement_time_msec` across the session's events. |
| `revenue_usd` | Sum 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](https://mastheadata.com/bigquery/errors/cannot-read-and-write-in-different-locations.md)).
*   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](https://mastheadata.com/glossary/backfill.md) 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.

## Related

[Make GA4 BigQuery queries cheaper: \TABLE\SUFFIX, columns, maximum bytes billed](https://mastheadata.com/bigquery/ga4/query-cost-control.md)[Build GA4 sessions in BigQuery from ga\session\id](https://mastheadata.com/bigquery/ga4/session-id.md)[Session source / medium in GA4 BigQuery](https://mastheadata.com/bigquery/ga4/session-source-medium.md)[Engagement rate and engaged sessions in GA4 BigQuery](https://mastheadata.com/bigquery/ga4/engagement-rate.md)[Query GA4 intraday tables together with daily tables](https://mastheadata.com/bigquery/ga4/intraday-tables.md)

*   [PARTITION BY](https://mastheadata.com/bigquery/sql/partition-by.md)
*   [CLUSTER BY](https://mastheadata.com/bigquery/sql/cluster-by.md)
*   [DELETE](https://mastheadata.com/bigquery/sql/delete.md)
*   [INSERT](https://mastheadata.com/bigquery/sql/insert.md)
*   [CREATE MATERIALIZED VIEW](https://mastheadata.com/bigquery/sql/create-materialized-view.md)
*   [Idempotent pipeline](https://mastheadata.com/glossary/idempotent-pipeline.md)

[All GA4 export queries](https://mastheadata.com/bigquery/ga4.md) · [BigQuery cost queries](https://mastheadata.com/bigquery/cost-queries.md) · [The GA4 sample dataset](https://mastheadata.com/bigquery/public-datasets/ga4-obfuscated-sample-ecommerce.md)
---

## Other pages in ga4

> For the full index of this section, see [BigQuery Reference](https://mastheadata.com/llms/llms-bigquery-reference.txt).

- [Bounce rate by landing page in GA4 BigQuery | GA4 BigQuery Export | Masthead](https://mastheadata.com/bigquery/ga4/bounce-rate.md): In GA4, bounce rate is the share of sessions that were not engaged: 1 minus engagement rate. In BigQuery, flag each session engaged if any event has session_engaged = '1', take the landing page from its first page_view, and divide non-engaged sessions by sessions.
- [Users and sessions by device and browser in GA4 BigQuery | GA4 BigQuery Export | Masthead](https://mastheadata.com/bigquery/ga4/device-and-browser.md): The device record in the GA4 export holds category (desktop, mobile, tablet), operating_system and web_info.browser. Group by those fields to count users and sessions. Reading only the subfields you need costs a fraction of the whole record.
- [Ecommerce funnel from view_item to purchase in GA4 BigQuery | GA4 BigQuery Export | Masthead](https://mastheadata.com/bigquery/ga4/ecommerce-funnel.md): Build a GA4 checkout funnel by flagging, per user, which of view_item, add_to_cart, begin_checkout, add_shipping_info, add_payment_info and purchase they reached, each step requiring the previous ones. It reads only event_name and user_pseudo_id, so it is cheap.
- [Engagement rate and engaged sessions in GA4 BigQuery | GA4 BigQuery Export | Masthead](https://mastheadata.com/bigquery/ga4/engagement-rate.md): Engagement rate in GA4 is engaged sessions divided by sessions. In the export a session is engaged when any of its events has session_engaged = '1'. Group events by user_pseudo_id and ga_session_id, flag engaged sessions with LOGICAL_OR, then divide.
- [Engagement time from engagement_time_msec in GA4 BigQuery | GA4 BigQuery Export | Masthead](https://mastheadata.com/bigquery/ga4/engagement-time.md): GA4 engagement time is the sum of the engagement_time_msec parameter across events. Sum it per day and divide by active users to get average engagement time per active user, or by sessions for engagement time per session. Wall-clock session length is a different number.
- [Count GA4 events by name in BigQuery | GA4 BigQuery Export | Masthead](https://mastheadata.com/bigquery/ga4/events-count.md): Count GA4 events with COUNT(*) grouped by event_name. It reads one small column, so it is the cheapest query on the export and the first one to compare with the Event count in GA4. The whole public sample costs about 53 MiB.
- [GA4 BigQuery export schema: tables, nested fields and value types | GA4 BigQuery Export | Masthead](https://mastheadata.com/bigquery/ga4/ga4-export-schema.md): The GA4 export writes one table per day (events_YYYYMMDD) and, with streaming on, events_intraday_YYYYMMDD. Each row is one event. Parameters, user properties and items are repeated records you read with UNNEST. This query lists every event parameter and which value column holds it.
- [Why GA4 BigQuery numbers differ from the GA4 interface | GA4 BigQuery Export | Masthead](https://mastheadata.com/bigquery/ga4/ga4-vs-ui-differences.md): BigQuery holds raw events, while GA4 reports estimate users and sessions with HyperLogLog++, may apply thresholds, sampling and consent-mode modeling, use the reporting identity and time zone, and show active users. Google expects a 2 to 5 percent gap in total event counts.
- [Users and sessions by country and city in GA4 BigQuery | GA4 BigQuery Export | Masthead](https://mastheadata.com/bigquery/ga4/geo-country-city.md): The geo record in the GA4 export holds continent, sub_continent, country, region, city and metro, derived from the user's IP address. Group by geo.country and geo.city to count users and sessions; selecting single fields keeps the scan small.
- [Query GA4 intraday tables together with daily tables | GA4 BigQuery Export | Masthead](https://mastheadata.com/bigquery/ga4/intraday-tables.md): With streaming export on, GA4 writes today's events to events_intraday_YYYYMMDD and deletes it once the daily table is complete. events_* matches both, so filter _TABLE_SUFFIX for both name patterns, strip the intraday_ prefix to get the date, and prefer the daily table when both exist.
- [Item revenue and units sold in GA4 BigQuery | GA4 BigQuery Export | Masthead](https://mastheadata.com/bigquery/ga4/items-revenue.md): Item-level ecommerce data in the GA4 export is the repeated items record. UNNEST(items) on purchase events gives one row per item sold, with item_name, item_category, quantity and item_revenue_in_usd. Sum them per item for units and revenue.
- [Key events (conversions) and conversion rate in GA4 BigQuery | GA4 BigQuery Export | Masthead](https://mastheadata.com/bigquery/ga4/key-events-conversions.md): The GA4 export has no flag for key events (formerly conversions): you list your key event names in SQL. Count them, count sessions and users that triggered them, and divide by all sessions or users to get session and user key event rates.
- [Landing pages in GA4 BigQuery | GA4 BigQuery Export | Masthead](https://mastheadata.com/bigquery/ga4/landing-pages.md): A landing page is the first page_view of a session. Group page views by user_pseudo_id and ga_session_id, take the page_location of the earliest one with ARRAY_AGG ORDER BY event_timestamp LIMIT 1, then count sessions per landing page.
- [New vs returning users in GA4 BigQuery | GA4 BigQuery Export | Masthead](https://mastheadata.com/bigquery/ga4/new-vs-returning-users.md): In the GA4 export a new user is one who logged first_visit (first_open in apps) in the period; everyone else active in the period is returning. Flag first_visit per user and day with LOGICAL_OR, then split the daily user count.
- [Page views by page in GA4 BigQuery | GA4 BigQuery Export | Masthead](https://mastheadata.com/bigquery/ga4/page-views.md): Page views in the GA4 export are page_view events. Read the URL from the page_location parameter, strip the query string, and count events and distinct users per page. The event_name filter does not reduce bytes; the date range and the columns do.
- [Purchases, revenue and average order value in GA4 BigQuery | GA4 BigQuery Export | Masthead](https://mastheadata.com/bigquery/ga4/purchases-and-revenue.md): GA4 purchase revenue is in ecommerce.purchase_revenue_in_usd (and purchase_revenue in your currency) on purchase events. Sum it per day, count distinct ecommerce.transaction_id for orders, and divide for average order value. It needs no UNNEST and scans little.
- [Make GA4 BigQuery queries cheaper: _TABLE_SUFFIX, columns, maximum bytes billed | GA4 BigQuery Export | Masthead](https://mastheadata.com/bigquery/ga4/query-cost-control.md): On-demand BigQuery bills the columns a query reads in every table it touches. For the GA4 export, filter _TABLE_SUFFIX with a constant range, select only the columns you need, keep event_params and items out unless required, and set maximum_bytes_billed. On the sample, that cuts one query from 3.34 GiB to 18.5 MiB.
- [Scroll depth by page in GA4 BigQuery | GA4 BigQuery Export | Masthead](https://mastheadata.com/bigquery/ga4/scroll-depth.md): GA4 enhanced measurement sends one scroll event per page the first time 90% of its height becomes visible. Count scroll and page_view events per page_location to get the share of page views that reached the bottom. Other depths need your own tracking.
- [Build GA4 sessions in BigQuery from ga_session_id | GA4 BigQuery Export | Masthead](https://mastheadata.com/bigquery/ga4/session-id.md): A GA4 session is identified by user_pseudo_id plus the ga_session_id event parameter. ga_session_id is the session start time in seconds, so it is not unique on its own. Group events by both to get one row per session with its start, length, events and page views.
- [Session source / medium in GA4 BigQuery | GA4 BigQuery Export | Masthead](https://mastheadata.com/bigquery/ga4/session-source-medium.md): Older GA4 exports, including the public sample, carry source, medium and campaign as event parameters. Take the first non-null source and medium in each session; sessions with none are direct. Newer exports have session_traffic_source_last_click, which is closer to GA4's session attribution.
- [Count GA4 sessions in BigQuery | GA4 BigQuery Export | Masthead](https://mastheadata.com/bigquery/ga4/sessions.md): Count GA4 sessions as distinct user_pseudo_id plus ga_session_id, the way GA4 does. Counting session_start events is cheaper but misses sessions that began before the date range. Compute the count over the whole period, because sessions crossing midnight appear on two days.
- [First user source, medium and campaign in GA4 BigQuery | GA4 BigQuery Export | Masthead](https://mastheadata.com/bigquery/ga4/traffic-source.md): The traffic_source record in the GA4 export is first-touch acquisition: the source, medium and campaign that first brought the user, the same on every later event. Count distinct users by traffic_source.source and medium; it reads only those subfields, so it is cheap.
- [Unnest GA4 event_params in BigQuery | GA4 BigQuery Export | Masthead](https://mastheadata.com/bigquery/ga4/unnest-event-params.md): Read a GA4 event parameter with a scalar subquery over UNNEST(event_params): (SELECT value.string_value FROM UNNEST(event_params) WHERE key = 'page_location'). It keeps one row per event, returns NULL when the parameter is missing and lets you pull several parameters side by side.
- [GA4 user_id vs user_pseudo_id in BigQuery | GA4 BigQuery Export | Masthead](https://mastheadata.com/bigquery/ga4/user-id-vs-pseudo-id.md): user_pseudo_id identifies a browser or app instance; user_id is the login ID you set yourself, NULL until you send it. Count people by mapping each user_pseudo_id to the user_id seen on any of its events, then counting COALESCE(user_id, user_pseudo_id).
- [Query GA4 user properties in BigQuery | GA4 BigQuery Export | Masthead](https://mastheadata.com/bigquery/ga4/user-properties.md): GA4 exports user properties in the repeated user_properties record on each event, with key, value slots and set_timestamp_micros. List the keys with UNNEST, read one with a scalar subquery, and keep the latest value per user with ARRAY_AGG ordered by set_timestamp_micros.
- [Weekly user retention cohorts in GA4 BigQuery | GA4 BigQuery Export | Masthead](https://mastheadata.com/bigquery/ga4/user-retention-cohorts.md): Assign each user to the week of their first_visit, find the weeks they were active afterwards, and count users per cohort and week offset. Dividing by the cohort size gives the retention table GA4 shows in cohort explorations. It needs only three small columns.
- [Count total, active and new users in GA4 BigQuery | GA4 BigQuery Export | Masthead](https://mastheadata.com/bigquery/ga4/users.md): Total users in GA4 BigQuery is COUNT(DISTINCT user_pseudo_id). Active users, the number GA4 reports show, are users with an engaged session, a first_visit event or an engagement_time_msec parameter. New users logged first_visit. Compute all three over the whole range, not per day.
- [GA4 BigQuery Export: SQL Queries for Sessions, Users, Events and Revenue | Masthead](https://mastheadata.com/bigquery/ga4.md): 28 SQL recipes for the GA4 BigQuery export: unnest event_params, sessions, users, traffic sources, engagement, ecommerce, retention, and how to keep the queries cheap. Every one runs on Google's public GA4 sample.
