r/bigquery • u/delta11235813 • 1h ago
A staging view pattern for the GA4 export that saves re-writing UNNEST subqueries in every query
If you query the GA4 export (events_*) regularly, you probably paste the same (SELECT value... FROM UNNEST(event_params) WHERE key = ...) subqueries into every analysis. I did, for longer than I care to admit.
What worked for me: one staging view that extracts the handful of parameters almost every query needs — session ID (properly: user_pseudo_id + ga_session_id), page_location, page_title, engagement_time_msec, plus session source/medium (from the session_start row's collected_traffic_source) and device/geo — and then writing all analysis against the view.
CREATE OR REPLACE VIEW `project.staging.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.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.analytics_123456789.events_*`
WHERE _TABLE_SUFFIX >= FORMAT_DATE('%Y%m%d', DATE_SUB(CURRENT_DATE, INTERVAL 90 DAY));
Notes / trade-offs, since this sub will rightly ask:
- Yes, the view re-scans the export on every query against it — it's an organisation pattern, not a cost optimisation. The
_TABLE_SUFFIXfilter bounds it to the last 90 days so that re-scan stays in check (widen it deliberately if you need longer history). If scan cost is your problem, materialise a daily flattened table instead; I use the view for ad-hoc and the materialised table for dashboards. - Taking source/medium from
collected_traffic_sourceon thesession_startevent only is the part I'd most recommend stealing — doing it ad hoc per query is where attribution quietly diverges between reports.session_source/session_mediumare NULL on every other row by design, so aggregate them per session (MAX(session_source)grouped bysession_id). - The silent-NULL trap applies here too: wrong typed value field (
string_valuevsint_value) returns NULL, not an error. Worth a key-inventory query on your own export before trusting any of this.
Disclosure: this pattern is from a template pack I sell (GA4 × BigQuery SQL templates). Posting the pattern itself because it's the part people ask me about most; the full view + the other templates are what's in the pack.
