Sub topic 14
Going further: building path counts in BigQuery
This chapter assumes you can read basic SQL (joins, window functions, GROUP BY) and that your GA4 property is linked to BigQuery. It also assumes you know the previous chapters' vocabulary: node types, forward and backward paths, and the limits of Path exploration.
When BigQuery is the better tool
Path exploration is quick, but it has fixed behavior. You pick one node type, one starting or ending point, and a limited number of visible steps. You can't change how steps are ordered, which events count as steps, or how a path is defined. BigQuery removes those constraints. Querying the raw export lets you do four things:
- Define exactly which events count as steps.
- Count paths per session, per user, or per day.
- Join paths to other tables, such as CRM or product data.
- Save the results as a table for dashboards.
The cost is that you now own the logic. Nothing in BigQuery tells you what a "step" is, so every decision the Path exploration made for you becomes your decision.
| Concern | Path exploration | BigQuery query |
|---|---|---|
| Step definition | Fixed by node type | Any column or combination |
| Starting or ending point | One node, chosen in the UI | Any SQL condition |
| Counting unit | Sessions and users shown in the diagram | Whatever you group by |
| Setup effort | A few clicks | Writing and testing SQL |
| Cost | None | Query bytes scanned |
| Sharing | Exploration link or export | Tables, scheduled queries, BI tools |
The export shape you will query
The daily export writes one table per day, named events_YYYYMMDD, with one row per event. Each row has:
user_pseudo_id, the pseudonymous device or browser identifier.event_name.event_timestamp, in microseconds.event_params, a repeated record of key and value pairs.
The session ID is not a top-level column. It lives in event_params under the key ga_session_id, so you extract it with a subquery over UNNEST(event_params).
ga_session_id is only unique within one user. Two users can share a value, so every partition and join must use user_pseudo_id and session_id together.
Step-to-step transitions
The simplest path count looks at pairs: how often does event A come immediately before event B in the same session? This query approximates the step-to-step volumes in a Path exploration.
WITH ordered AS (
SELECT
user_pseudo_id,
(SELECT value.int_value FROM UNNEST(event_params) WHERE key = 'ga_session_id') AS session_id,
event_name,
event_timestamp
FROM `my_project.analytics_123456789.events_*`
WHERE _TABLE_SUFFIX BETWEEN '20260101' AND '20260131'
),
paired AS (
SELECT
event_name AS from_event,
LEAD(event_name) OVER (
PARTITION BY user_pseudo_id, session_id
ORDER BY event_timestamp
) AS to_event
FROM ordered
)
SELECT from_event, to_event, COUNT(*) AS transitions
FROM paired
WHERE to_event IS NOT NULL
GROUP BY from_event, to_event
ORDER BY transitions DESC
LIMIT 20;The query works in four stages:
orderedpulls the three fields a path needs and restricts the date range. The_TABLE_SUFFIXfilter limits how many daily tables BigQuery scans, which controls cost.pairedusesLEADto attach the next event's name to each row. The window is partitioned by user and session and ordered by time, so the "next" event never crosses a session boundary.- The outer query drops the last event of each session, which has no successor, and counts each pair.
ORDER BY ... LIMIT 20shows the most common transitions first.
The output is a flat list of edges. Each row corresponds to one link between two nodes in the diagram. It is not a tree, because it has no memory of how the user reached from_event.
Forward paths from a starting point
To mimic a forward Path exploration you need the first few steps after a chosen starting event, kept together as one path. Number the events in each session, find the starting event, then collect the next steps. This example starts at select_promotion, the event from the instrumentation chapter, and follows three steps after it.
WITH events AS (
SELECT
user_pseudo_id,
(SELECT value.int_value FROM UNNEST(event_params) WHERE key = 'ga_session_id') AS session_id,
event_name,
event_timestamp
FROM `my_project.analytics_123456789.events_*`
WHERE _TABLE_SUFFIX BETWEEN '20260101' AND '20260131'
AND event_name NOT IN ('session_start', 'first_visit', 'user_engagement')
),
numbered AS (
SELECT
user_pseudo_id,
session_id,
event_name,
ROW_NUMBER() OVER (
PARTITION BY user_pseudo_id, session_id
ORDER BY event_timestamp, event_name
) AS step_number
FROM events
WHERE session_id IS NOT NULL
),
starts AS (
SELECT user_pseudo_id, session_id, MIN(step_number) AS start_step
FROM numbered
WHERE event_name = 'select_promotion'
GROUP BY user_pseudo_id, session_id
),
following AS (
SELECT
n.user_pseudo_id,
n.session_id,
n.event_name,
n.step_number - s.start_step AS steps_after_start
FROM numbered AS n
JOIN starts AS s
ON n.user_pseudo_id = s.user_pseudo_id
AND n.session_id = s.session_id
WHERE n.step_number BETWEEN s.start_step AND s.start_step + 3
),
session_paths AS (
SELECT
user_pseudo_id,
session_id,
STRING_AGG(event_name, ' > ' ORDER BY steps_after_start) AS path
FROM following
GROUP BY user_pseudo_id, session_id
)
SELECT path, COUNT(*) AS sessions
FROM session_paths
GROUP BY path
ORDER BY sessions DESC
LIMIT 20;Each row of the result is a complete path, such as select_promotion > page_view > scroll > add_to_cart, with the number of sessions that followed it.
The query makes four choices that Path exploration would otherwise make for you:
- Automatic events are excluded.
session_start,first_visitanduser_engagementoften add noise between meaningful steps. Change the list to suit your question. - Only the first start per session counts.
MIN(step_number)ignores later occurrences of the starting event. Remove theGROUP BYlogic if you want every occurrence. - Ties are broken by event name. Several events can share one
event_timestamp. Theevent_nametiebreak keeps results stable, but the order of tied events is arbitrary. - Sessions without an ID are dropped.
session_id IS NOT NULLremoves rows that would otherwise all land in one partition.
Backward paths to an ending point
For a backward path, anchor on the ending event and look at the steps before it. Reuse the events and numbered CTEs from the forward query. Then change starts to find the last occurrence of the ending event, and change the filter in following to a negative window:
-- Replace the starts and following CTEs with:
ends AS (
SELECT user_pseudo_id, session_id, MAX(step_number) AS end_step
FROM numbered
WHERE event_name = 'purchase'
GROUP BY user_pseudo_id, session_id
),
preceding AS (
SELECT
n.user_pseudo_id,
n.session_id,
n.event_name,
n.step_number - e.end_step AS steps_before_end
FROM numbered AS n
JOIN ends AS e
ON n.user_pseudo_id = e.user_pseudo_id
AND n.session_id = e.session_id
WHERE n.step_number BETWEEN e.end_step - 3 AND e.end_step
)Aggregate preceding with STRING_AGG(event_name, ' > ' ORDER BY steps_before_end). The result lists how sessions that reached purchase got there.
Differences you should expect from the UI
Your BigQuery counts will rarely match the Path exploration exactly. Common reasons:
- Different step definitions. The UI uses one node type, such as page title or event name. Your query uses event names only, unless you add page parameters.
- Different filtering. The UI may omit or collapse some automatic events. You choose your own list.
- Different counting units. The UI shows users and sessions in its own way. A SQL
COUNT(*)counts whatever rows you group. - Data timing. The daily export lags. Today's data may exist only in
events_intraday_*, so a query onevents_*can miss recent activity. - Different processing. The export contains unsampled event rows. Reports and explorations can apply their own processing, thresholds and sampling.
Treat BigQuery as an independent, more transparent measurement of the same behavior. Agreement in direction and rough size is a good sign. Exact equality isn't a realistic goal.
Extending the query to page paths
Event names often hide the pages users saw. To follow pages instead, extract page_location or page_title from event_params and filter to page_view. Add it to the events CTE:
(SELECT value.string_value FROM UNNEST(event_params) WHERE key = 'page_location') AS page_locationThen replace event_name with a cleaned version of page_location. Strip query strings with REGEXP_EXTRACT(page_location, r'^https?://[^/]+([^?#]*)'), or paths such as /product?id=1 and /product?id=2 will count as different steps. This mirrors the "page path" node type and avoids the same fragmentation problem you meet in the UI.
Checking your work
Before you trust a path query, run three checks:
- Pick one real session by
user_pseudo_idandsession_id. List its events in order and confirm your path string matches. - Compare a top-level total, such as the number of sessions containing your starting event, with the same count in GA4 reporting. Expect a small gap, not a large one.
- Re-run the query with a different tiebreak in
ORDER BY. If the top paths change, your results depend on arbitrary ordering.
Exercise
You run the forward-path query and see that the most common path is select_promotion > select_promotion > select_promotion > select_promotion. Name one likely cause and one change to the query that would address it.
Show answer
The tracking probably fires the same event repeatedly, for example on every banner impression or on repeated clicks, so consecutive steps repeat. You can either remove duplicates by keeping a row only when its event name differs from the previous one (use LAG(event_name) in a CTE and filter where it is not equal), or exclude the noisy event from the events CTE and rely on other events as steps. Checking the instrumentation for duplicate firing is also worthwhile.
Exercise
Why must the window in a path query be partitioned by both user_pseudo_id and session_id rather than by session_id alone?
Show answer
ga_session_id is only unique within a single user. Two different users can have the same value, so partitioning by session_id alone would mix their events into one sequence and create paths that no one actually followed.