DEV Community

関聖矢
関聖矢

Posted on

GA4 BigQuery UNNEST: How to Extract event_params Without the NULLs and Errors

GA4 BigQuery UNNEST: How to Extract event_params Without the NULLs and Errors

If you have exported GA4 to BigQuery, you have probably hit this moment: you open the events_* table, find the column that should hold the page URL or the session ID… and it's not a column at all. It's a nested, repeated record called event_params, and almost everything you actually want to analyse is buried inside it.

This is the single biggest reason people stall with the GA4 BigQuery export. The data is all there — page locations, session IDs, engagement time, campaign values, your custom parameters — but none of it is directly queryable until you UNNEST it correctly.

This guide covers the patterns I use in client work, the three mistakes that produce errors or silent NULLs, and how to stop repeating the same extraction code in every query.

Why event_params is nested in the first place

GA4 events are flexible by design. A page_view carries page_location and page_title; a purchase carries transaction values; your app may send dozens of custom parameters that another site never sends. Instead of a fixed column per parameter, BigQuery stores them as an array of key/value pairs:

  • key — the parameter name, e.g. page_location
  • value.string_value, value.int_value, value.float_value, value.double_value — the value, stored in exactly one of these typed fields depending on its type

That design is why a flat SELECT event_params.page_location cannot work, and why the extraction pattern below becomes the foundation of nearly every GA4 query you will ever write.

Pattern 1: Extract one or more parameters with a subquery

The most readable and most reusable approach is a scalar subquery per parameter:

SELECT
  event_date,
  event_timestamp,
  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 = 'page_location') AS page_location,
  (SELECT value.string_value FROM UNNEST(event_params) WHERE key = 'page_title') AS page_title,
  (SELECT value.string_value FROM UNNEST(event_params) WHERE key = 'page_referrer') AS page_referrer,
  (SELECT value.int_value FROM UNNEST(event_params) WHERE key = 'engagement_time_msec') AS engagement_time_msec
FROM `{{project_id}}.{{dataset}}.events_*`
WHERE _TABLE_SUFFIX BETWEEN '{{start_date}}' AND '{{end_date}}';
Enter fullscreen mode Exit fullscreen mode

A few things to notice:

  • Each parameter is pulled out with its own typed field. ga_session_id is an integer, so it comes from value.int_value. page_location is a string, so it comes from value.string_value. Get the type wrong and you don't get an error — you get NULL, silently, on every row (more on that below).
  • The WHERE _TABLE_SUFFIX BETWEEN ... clause is not optional decoration. Without it, BigQuery scans every daily table in the dataset. On a property with a year of history, that is the difference between a cheap query and an expensive surprise.
  • This pattern scales fine. Five parameters, ten parameters — the query stays readable, and each line can be copied into other queries as-is.

One nuance: if the same key somehow appears twice in one event, this subquery form will fail with a "scalar subquery produced more than one element" error. In standard GA4 exports that is rare, but if you hit it, add LIMIT 1 inside the subquery while you investigate your tagging.

Pattern 2: Build a proper session ID (and why ga_session_id alone is wrong)

Once you can extract ga_session_id, the next trap is using it on its own. Don't. ga_session_id is a timestamp-based value that is only unique within a user. Two different users can absolutely share the same ga_session_id, so counting distinct ga_session_id values undercounts sessions and joining on it creates phantom matches.

The fix is to combine it with user_pseudo_id:

SELECT
  event_date,
  COUNT(DISTINCT
    CONCAT(
      user_pseudo_id, '.',
      CAST(
        (SELECT value.int_value
         FROM UNNEST(event_params)
         WHERE key = 'ga_session_id') AS STRING)
    )
  ) AS session_count
FROM `{{project_id}}.{{dataset}}.events_*`
WHERE _TABLE_SUFFIX BETWEEN '{{start_date}}' AND '{{end_date}}'
GROUP BY event_date
ORDER BY event_date;
Enter fullscreen mode Exit fullscreen mode

With that definition, a daily session count becomes a straightforward COUNT(DISTINCT ...) grouped by event_date, and it reconciles far better against the GA4 interface. (It will rarely match the UI exactly — the GA4 UI applies its own processing and, for some reports, estimation. A small, explainable gap is normal; a large one usually means the session definition, not the data, is wrong.)

If your site issues a signed-in user_id, consider building the session ID from that instead of user_pseudo_id — it stitches sessions across devices, which cookie-based IDs cannot do.

Pattern 3: UNNEST the items array for product-level data

E-commerce data lives in a different nested field: items. Unlike event_params, you usually want one row per item, so instead of a subquery you join the unnested array:

SELECT
  event_date,
  user_pseudo_id,
  item.item_id,
  item.item_name,
  item.item_category,
  item.price,
  item.quantity
FROM `{{project_id}}.{{dataset}}.events_*`
CROSS JOIN UNNEST(items) AS item
WHERE _TABLE_SUFFIX BETWEEN '{{start_date}}' AND '{{end_date}}'
  AND event_name = 'purchase';
Enter fullscreen mode Exit fullscreen mode

Two gotchas here:

  1. CROSS JOIN UNNEST drops events with no items. For purchase or view_item that is normally what you want. If you are analysing an event type where some rows have items and some don't, and the item-less rows still matter, switch to LEFT JOIN UNNEST(items) AS item.
  2. Never write items.item_name directly. items is an array; referencing a field on it without UNNESTing produces the classic error: Cannot access field item_name on a value with type ARRAY<...>. That error message is practically a rite of passage — if you've seen it, this pattern is the fix.

The same subquery approach from Pattern 1 also works for user_properties — for example pulling first_open_time or your own custom user properties such as a membership tier — just UNNEST user_properties instead of event_params.

The 3 mistakes that waste the most time

1. Wrong key name. The session ID parameter is ga_session_id, not session_id. Custom parameters are worse: the key must match exactly what your implementation sends. When in doubt, query the distinct keys present in your own export before writing analysis SQL — guessing key names is how you get a full column of NULLs that looks like "no data."

2. Wrong value type. Every parameter value lives in exactly one typed field. Read an integer parameter via value.string_value and you get NULL, not an error, which makes this the most dangerous mistake of the three — your query "works" and your report is wrong. Check the schema tab in the BigQuery console, or run a key inventory that counts how often each key appears with each value type.

3. Forgetting the date filter. A missing _TABLE_SUFFIX condition means a full-dataset scan: slower, more expensive, and occasionally wrong, because intraday (streaming) tables can be included in the wildcard depending on how you reference the tables. Note that intraday data is provisional — values can change or be replaced — so keep it out of anything you report as final. Always check the "bytes processed" estimate in the console before running a new query over a long period.

Stop copy-pasting: turn the patterns into a view

If you find yourself pasting the same five subqueries into every analysis — and you will — promote them into a staging view once, and write short queries against the view from then on:

CREATE OR REPLACE VIEW `{{project_id}}.{{staging_dataset}}.stg_events` AS
SELECT
  PARSE_DATE('%Y%m%d', event_date) AS event_date,
  event_timestamp,
  event_name,
  user_pseudo_id,
  CONCAT(
    user_pseudo_id, '.',
    CAST((SELECT value.int_value FROM UNNEST(event_params) WHERE key = 'ga_session_id') AS STRING)
  ) AS session_id,
  (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 = 'page_title') AS page_title,
  (SELECT value.int_value FROM UNNEST(event_params) WHERE key = 'engagement_time_msec') AS engagement_time_msec,
  CASE WHEN event_name = 'session_start' THEN collected_traffic_source.manual_source END AS session_source,
  CASE WHEN event_name = 'session_start' THEN collected_traffic_source.manual_medium END AS session_medium,
  device.category AS device_category,
  geo.country AS country
FROM `{{project_id}}.{{dataset}}.events_*`
WHERE _TABLE_SUFFIX BETWEEN '{{start_date}}' AND '{{end_date}}';
Enter fullscreen mode Exit fullscreen mode

Two things in this view deserve a second look:

  • The _TABLE_SUFFIX filter is doing real work. A view over events_* with no date filter scans every daily table in the dataset every time anyone queries it — the full-dataset scan from Mistake #3 above, now baked into every query you write against the view. The placeholders above keep the same replace-three-values convention as the other patterns; if you create the view once for repeated use, swap them for a rolling window instead (for example, _TABLE_SUFFIX between FORMAT_DATE('%Y%m%d', DATE_SUB(CURRENT_DATE(), INTERVAL 90 DAY)) and yesterday's date) so the scan stays bounded. Either way, always check the "bytes processed" estimate before running a new query against the view over a long period.
  • Source/medium is read from the session_start event only. collected_traffic_source in the GA4 export is an event-level struct, but the values that describe the session's traffic source are the ones carried on the session's session_start event — taking the struct from whichever event happens to be on the row is how attribution quietly diverges between reports. The CASE expressions above therefore return session_source / session_medium only on the session_start row and NULL on every other row, by design. For session-level reporting, aggregate them per session (MAX(session_source), MAX(session_medium) grouped by session_id); don't expect them to be populated event by event.

With the view in place, most day-to-day questions — sessions by channel, pageviews per session, engagement by device — become five-line queries instead of fifty-line ones.

Get the free sample pack

These patterns are templates 01 and 02 from a pack of 20 production GA4 × BigQuery SQL templates I use and maintain in client work — covering the basics above plus e-commerce funnels, channel CAC, LTV and cohort analysis, Search Console joins, and query-cost monitoring. Every template uses the same placeholders ({{project_id}}, {{dataset}}, date range), so you replace three values and run it.

You can download a free sample with 3 full templates (UNNEST patterns, session definition, and the e-commerce funnel) here: https://logicalweb.gumroad.com/l/qgozm

If the sample saves you time, the full pack of 20 is available here: https://logicalweb.gumroad.com/l/pksizb

— I run a GA4 × BigQuery consultancy in Japan (logical-web.jp) and write about this export for a living. If a query above doesn't reconcile with your data, the session definition and the intraday tables are the first two places to look.

Top comments (0)