GA4 in BigQuery · Users, sessions and traffic
Users and sessions by country and city in GA4 BigQuery
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.
The query
SELECT
geo.country,
geo.city,
COUNT(DISTINCT user_pseudo_id) AS users,
COUNT(DISTINCT CONCAT(user_pseudo_id, '.', CAST(
(SELECT value.int_value FROM UNNEST(event_params) WHERE key = 'ga_session_id') AS STRING))) AS sessions
FROM `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_*`
WHERE _TABLE_SUFFIX BETWEEN '20201201' AND '20201231'
GROUP BY country, city
ORDER BY sessions DESC
LIMIT 20;How it works
geo is a STRUCT with continent, sub_continent, country, region, city and metro. GA4 fills it per event from the IP address, so a traveling user can appear in several countries in one month.
The query counts users and sessions per country and city. Group by geo.country alone for a country report, or add geo.region between country and city when city names repeat across regions.
City-level location is approximate, and GA4 reports (not set) where it cannot determine it. Treat small cities with care in reports that leave your team: GA4 applies thresholds to some report data to protect privacy, and the export has no such protection.
| Column | Meaning |
|---|---|
country / city | Country and city from the geo record. |
users / sessions | Distinct users and sessions from that location. |
Notes and cost
- Cost:
geo.countryalone across the sample is 48.0 MiB, the wholegeorecord 287.6 MiB. This month, with the session key, costs 377.3 MiB; users per country without sessions costs 49.8 MiB. - Location fields describe each event, not the user. Counting users by country can put one user in two countries; pick one location per user (for example from
first_visit) if you need users to add up.
Variations
Users per country, no event_params
SELECT
geo.country,
COUNT(DISTINCT user_pseudo_id) AS users
FROM `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_*`
WHERE _TABLE_SUFFIX BETWEEN '20201201' AND '20201231'
GROUP BY country
ORDER BY users DESC;One country per user, from the first visit
SELECT
geo.country,
COUNT(DISTINCT user_pseudo_id) AS new_users
FROM `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_*`
WHERE _TABLE_SUFFIX BETWEEN '20201201' AND '20201231'
AND event_name = 'first_visit'
GROUP BY country
ORDER BY new_users DESC;FAQ
How is geo determined in GA4 BigQuery?
From the IP address of each event. It is stored per event in the geo record, so it can change during a user's visits.
Why do users by country add up to more than total users?
Users who appear in several countries in the range are counted once in each. Assign one country per user if you need totals to match.
Related
All GA4 export queries · BigQuery cost queries · The GA4 sample dataset
