Sub topic 10
Analysing AI referrals in the BigQuery export
The GA4 interface is good for checking trends. The BigQuery export gives you the raw events, so you can apply your own session logic, join other tables, and keep history beyond GA4's retention limits. This chapter shows how to find AI assistant visits in the export, count sessions per assistant, and attach landing pages, engagement, and conversions to them.
Prerequisites
This chapter assumes you can:
- Read basic SQL (
SELECT,WHERE,GROUP BY, CTEs). - Reach a GA4 property with the BigQuery link already enabled. Linking is set up in Admin under BigQuery links, and data only exists from the day the link was created.
- Explain what a referrer and a UTM parameter are, as covered earlier in this tutorial.
What the export looks like
GA4 writes one table per day, named events_YYYYMMDD, in a dataset named analytics_<property_id>. A streaming export also writes events_intraday_YYYYMMDD for the current day. Each row is one event. The columns that matter here are:
| Column or parameter | Meaning |
|---|---|
| `event_date`, `event_timestamp` | Date as a `YYYYMMDD` string, and event time in microseconds |
| `event_name` | For example `page_view`, `session_start`, `purchase` |
| `user_pseudo_id` | Browser or app instance identifier |
| `event_params` | Repeated key/value records, which you must unnest |
| `ga_session_id` (inside `event_params`) | Session start timestamp, unique only within one `user_pseudo_id` |
| `page_referrer`, `page_location` (inside `event_params`) | Previous URL and current URL |
Two details cause most beginner errors. First, the export has no session_id column, so a session key is the pair user_pseudo_id plus ga_session_id. Second, each parameter value sits in one of four typed fields (string_value, int_value, float_value, double_value), so you must pick the right one.
The approach
The key design choice is to classify a session by its first page view only. Later page views in the same session have your own site as the referrer, so classifying every event would count internal navigation or miss the session altogether.
Step 1: Count page views by referrer host
Start with the simple query from the plan. It counts page views per day whose referrer matches a known assistant host. It is useful for discovering which hosts appear in your data before you build a classification.
SELECT
PARSE_DATE('%Y%m%d', event_date) AS day,
REGEXP_EXTRACT(page_referrer, r'^https?://([^/]+)') AS referrer_host,
COUNT(*) AS page_views
FROM (
SELECT
event_date,
(SELECT value.string_value FROM UNNEST(event_params) WHERE key = 'page_referrer') AS page_referrer
FROM `my_project.analytics_123456789.events_*`
WHERE event_name = 'page_view'
AND _TABLE_SUFFIX BETWEEN '20261101' AND '20261130'
)
WHERE REGEXP_CONTAINS(page_referrer, r'(chatgpt\.com|chat\.openai\.com|gemini\.google\.com|perplexity\.ai|copilot\.microsoft\.com|claude\.ai)')
GROUP BY day, referrer_host
ORDER BY day, page_views DESC;Replace my_project and analytics_123456789 with your project and dataset. The scalar subquery (SELECT value.string_value FROM UNNEST(event_params) WHERE key = ...) is the standard way to pull one parameter out of the repeated field.
Step 2: Classify sessions by assistant
Page views are not sessions. The next query reduces each session to its first page_view, then labels it from two signals: the referrer host and the utm_source value in page_location. Using both matters because some assistants add UTM parameters to links, and an assistant may send a referrer, a UTM tag, both, or neither. Check which of these your own data shows before trusting the mapping.
WITH events AS (
SELECT
user_pseudo_id,
event_name,
event_timestamp,
(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_referrer') AS page_referrer
FROM `my_project.analytics_123456789.events_*`
WHERE _TABLE_SUFFIX BETWEEN '20261101' AND '20261130'
AND event_name = 'page_view'
),
landing AS (
SELECT
user_pseudo_id,
ga_session_id,
page_location,
NET.HOST(page_referrer) AS ref_host,
REGEXP_EXTRACT(page_location, r'[?&]utm_source=([^&#]*)') AS utm_source
FROM events
WHERE ga_session_id IS NOT NULL
QUALIFY ROW_NUMBER() OVER (
PARTITION BY user_pseudo_id, ga_session_id
ORDER BY event_timestamp
) = 1
)
SELECT
CASE
WHEN REGEXP_CONTAINS(ref_host, r'(^|\.)(chatgpt\.com|chat\.openai\.com)$')
OR utm_source = 'chatgpt.com' THEN 'ChatGPT'
WHEN REGEXP_CONTAINS(ref_host, r'(^|\.)gemini\.google\.com$') THEN 'Gemini'
WHEN REGEXP_CONTAINS(ref_host, r'(^|\.)perplexity\.ai$') THEN 'Perplexity'
WHEN REGEXP_CONTAINS(ref_host, r'(^|\.)copilot\.microsoft\.com$') THEN 'Copilot'
WHEN REGEXP_CONTAINS(ref_host, r'(^|\.)claude\.ai$') THEN 'Claude'
END AS assistant,
COUNT(*) AS sessions
FROM landing
GROUP BY assistant
HAVING assistant IS NOT NULL
ORDER BY sessions DESC;Points worth noting:
NET.HOSTextracts the host from a URL and returnsNULLfor aNULLinput. ACASEbranch that evaluates toNULLis treated as false, so sessions with no referrer simply fall through.- The anchored pattern
(^|\.)perplexity\.ai$matchesperplexity.aiandwww.perplexity.ai, but notnotperplexity.aiorperplexity.ai.example.com. The unanchored regex in Step 1 would match both of those, which is acceptable for exploration and wrong for reporting. QUALIFYfilters on a window function result. BigQuery requires aWHERE,GROUP BY, orHAVINGclause in the same query block, and theWHEREhere satisfies that.- Sessions without a
ga_session_idare dropped, since they cannot be keyed.
Step 3: Add landing pages, engagement, and conversions
Now compute per-session metrics and join them to the classified landing rows. This version reads every event type, so it scans more data than Step 2.
WITH events AS (
SELECT
user_pseudo_id,
event_name,
event_timestamp,
(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_referrer') AS page_referrer,
(SELECT value.int_value FROM UNNEST(event_params) WHERE key = 'engagement_time_msec') AS engagement_time_msec,
(SELECT COALESCE(value.int_value, SAFE_CAST(value.string_value AS INT64))
FROM UNNEST(event_params) WHERE key = 'session_engaged') AS session_engaged
FROM `my_project.analytics_123456789.events_*`
WHERE _TABLE_SUFFIX BETWEEN '20261101' AND '20261130'
),
landing AS (
SELECT
user_pseudo_id,
ga_session_id,
REGEXP_EXTRACT(page_location, r'^https?://[^/]+([^?#]*)') AS landing_path,
NET.HOST(page_referrer) AS ref_host,
REGEXP_EXTRACT(page_location, r'[?&]utm_source=([^&#]*)') AS utm_source
FROM events
WHERE event_name = 'page_view' AND ga_session_id IS NOT NULL
QUALIFY ROW_NUMBER() OVER (
PARTITION BY user_pseudo_id, ga_session_id
ORDER BY event_timestamp
) = 1
),
metrics AS (
SELECT
user_pseudo_id,
ga_session_id,
IFNULL(SUM(engagement_time_msec), 0) / 1000 AS engagement_seconds,
LOGICAL_OR(IFNULL(session_engaged, 0) = 1) AS engaged,
COUNTIF(event_name = 'generate_lead') AS conversions
FROM events
WHERE ga_session_id IS NOT NULL
GROUP BY user_pseudo_id, ga_session_id
)
SELECT
CASE
WHEN REGEXP_CONTAINS(l.ref_host, r'(^|\.)(chatgpt\.com|chat\.openai\.com)$')
OR l.utm_source = 'chatgpt.com' THEN 'ChatGPT'
WHEN REGEXP_CONTAINS(l.ref_host, r'(^|\.)gemini\.google\.com$') THEN 'Gemini'
WHEN REGEXP_CONTAINS(l.ref_host, r'(^|\.)perplexity\.ai$') THEN 'Perplexity'
WHEN REGEXP_CONTAINS(l.ref_host, r'(^|\.)copilot\.microsoft\.com$') THEN 'Copilot'
WHEN REGEXP_CONTAINS(l.ref_host, r'(^|\.)claude\.ai$') THEN 'Claude'
END AS assistant,
l.landing_path,
COUNT(*) AS sessions,
ROUND(COUNTIF(m.engaged) / COUNT(*), 3) AS engagement_rate,
ROUND(AVG(m.engagement_seconds), 1) AS avg_engagement_seconds,
SUM(m.conversions) AS conversions
FROM landing AS l
JOIN metrics AS m USING (user_pseudo_id, ga_session_id)
GROUP BY assistant, l.landing_path
HAVING assistant IS NOT NULL
ORDER BY sessions DESC
LIMIT 50;Replace generate_lead with the key event names your property uses. The COALESCE on session_engaged accepts either an integer or a string value, because the typed field used for that parameter can differ between exports.
Reading the results
Treat the output as a ranked list of pages that assistants actually send people to. Compare engagement_rate and avg_engagement_seconds across assistants only when each has enough sessions. A row with 12 sessions and a 0.75 rate tells you very little. If one landing path dominates, check whether the assistant is quoting that page directly or whether a single link was shared widely.
Why export numbers differ from the GA4 interface
Other limits that carry over from earlier chapters still apply here:
- Visits with no referrer and no UTM tag cannot be classified. They stay in the unclassified rows, usually labelled direct.
- Crawler requests from AI systems do not run your JavaScript tag, so they never appear in the export.
- Older data is missing if the BigQuery link was created recently.
Common errors
- Counting
COUNT(DISTINCT ga_session_id)alone. The value is only unique per user, so two users can share one. Combine it withuser_pseudo_id. - Classifying every event rather than the first page view. This undercounts sessions, or credits internal navigation.
- Using
int_valuefor a parameter stored as a string, which returnsNULLsilently. - Forgetting
_TABLE_SUFFIX, which makes the query expensive.
Exercise
In Step 2, a session starts on a page reached from https://www.perplexity.ai/search?q=example. The user then clicks to a second page on your site. Which row of this session does the query use for classification, and what value does ref_host have?
Show answer
It uses the first page_view of the session, found with ROW_NUMBER() ... ORDER BY event_timestamp = 1. Its ref_host is www.perplexity.ai, which matches the Perplexity pattern (^|\.)perplexity\.ai$. The second page view has your own site as the referrer, so it is ignored.
Exercise
Extend the Step 3 query to report only sessions from Claude on a single day, 2026-11-15, and explain which part of the query should change to reduce the amount of data scanned.
Show answer
Add AND event_date = '20261115' is not enough to cut cost on its own. Change the _TABLE_SUFFIX filter to _TABLE_SUFFIX = '20261115' so only that day's table is read, then add WHERE assistant = 'Claude' through the existing HAVING assistant = 'Claude' condition in place of IS NOT NULL. The suffix filter reduces scanned data. The HAVING change only reduces output rows.