Skip to content

Google Analytics

Read Google Analytics 4 reports, realtime activity and property settings as tables

Connector software
Free and open source
Service credentials
Required
Use with an agent

Install the Orchard skill in your project to help your agent find connectors, configure them, and verify SQL results.

npx skills add Query-farm/vgi-skills --skill orchard

Copy this request into your coding agent to get started.

Use https://query.farm/products/orchard/connectors/google-analytics/index.md to help me query Google Analytics with DuckDB or Haybarn 2.0.1 and VGI protocol 3.4. Ask only for missing details about the result I need or whether I want local execution, self-hosting or Query Farm hosting. Check the connector's actual hosting availability, credentials and input requirements. Read one format of each needed reference and the exact object declarations before writing SQL. Use a released connector, and distinguish a saved example result from anything you actually execute. If you cannot run the query, tell me what remains to verify.

Track daily active users and sessions

Uses your connected account. Set up the connector and credentials to run it with your data.

SELECT property_id, date, activeUsers, sessions
FROM ga4.main.report('', dimensions => ['date'], metrics => ['activeUsers', 'sessions'])
ORDER BY property_id, date

Quick start

Choose where to run Google Analytics, then follow the steps below.

The connector runs alongside DuckDB or Haybarn. No Query Farm account is needed.

1. Install the vgi extension

Run this in your SQL client. On DuckDB, keep FROM query_farm on LOAD in later sessions.

setup.sql
SET allow_extension_repositories = 'allowed';

CREATE EXTENSION REPOSITORY IF NOT EXISTS query_farm
    WITH PREFIX 'https://duckdb-extensions.query.farm';

INSTALL vgi FROM query_farm;
LOAD vgi FROM query_farm;

2. Attach the connector

Attach with uvx

Needs uv. uvx builds the worker from its release tag on first attach and reuses the cached environment after that.

ATTACH 'ga4' AS ga4 (
  TYPE vgi,
  LOCATION 'uvx --from git+https://github.com/Query-farm/[email protected] vgi-google-analytics'
);

3. Add service credentials

After attaching, create the secret for the service you want to query in the same SQL session. Replace the placeholders with your service settings.

google_analytics credentials

Google Analytics credentials (scope analytics.readonly). Provide ONE of: service_account_json (a service-account key, the account added to the GA4 property as a Viewer); client_id + client_secret + refresh_token (an OAuth user grant); or access_token (short-lived). quota_project_id optionally bills API quota to a specific Google Cloud project.

Get these credentials β†’
secret.sql
CREATE SECRET google_analytics (
    TYPE google_analytics,
    service_account_json '<GOOGLE_ANALYTICS_SERVICE_ACCOUNT_JSON>',  -- secret
    client_id            '<client_id>',
    client_secret        '<GOOGLE_ANALYTICS_CLIENT_SECRET>',  -- secret
    refresh_token        '<REFRESH_TOKEN>',  -- secret
    access_token         '<ACCESS_TOKEN>',  -- secret
    quota_project_id     '<quota_project_id>'
);
Credential fields and requirements β†’

4. Run a query

query.sql
SELECT property_id, date, activeUsers, sessions
FROM ga4.main.report('', dimensions => ['date'], metrics => ['activeUsers', 'sessions'])
ORDER BY property_id, date
More example queries β†’
Technical details
Verified connector release
v0.2.1
Engine
2.0.1
VGI protocol
3.4.0
Verified on
December 1, 2026
Release notes on GitHub
Pin a version for production

When running the connector yourself, keep a specific release until you’re ready to upgrade. Replace the ATTACH statement above with this one and follow the same extension and credential setup.

Attach with uvx

Needs uv. uvx builds the worker from its release tag on first attach and reuses the cached environment after that.

ATTACH 'ga4' AS ga4 (
  TYPE vgi,
  LOCATION 'uvx --from git+https://github.com/Query-farm/[email protected] vgi-google-analytics'
);

Overview

Read-only Google Analytics 4: reports, realtime, metadata and property configuration

ATTACH options

credentials
Where credentials come from: 'auto' (default) uses the google_analytics secret and otherwise Application Default Credentials where the worker permits it; 'secret' requires the secret and never falls back; 'oauth' signs in locally through the browser to Query Farm's app and carries refreshable credentials in the client's opaque attach data.VARCHAR
report_page_size
Rows fetched per report() API request, up to 250000 (default 100000).BIGINT
data_api_url
Base URL of the GA4 Data API, for a proxy or a test double. Overriding it disables the Application Default Credentials fallback.VARCHAR
admin_api_url
Base URL of the GA4 Admin API, for a proxy or a test double. Overriding it disables the Application Default Credentials fallback.VARCHAR

Catalog

Everything ga4 exposes once attached β€” read straight from the worker's released build.

ga4 1 schema
main 3 tables Β· 13 functions

GA4 Data API and Admin API (read-only, analytics.readonly scope)

Schema examples (9)
Examples (9)

Every property this credential can read

SELECT account_name, property_id, property_name
FROM ga4.main.account_summaries
ORDER BY account_name, property_name;

Daily active users and sessions for the last 28 days, per property

SELECT property_id, date, activeUsers, sessions
FROM ga4.main.report('', dimensions => ['date'], metrics => ['activeUsers', 'sessions'])
ORDER BY property_id, date;

Sessions and key events by channel

SELECT property_id, sessionDefaultChannelGroup, sessions, keyEvents
FROM ga4.main.report('', dimensions => ['sessionDefaultChannelGroup'], metrics => ['sessions', 'keyEvents'])
ORDER BY property_id, sessions DESC;

Find the api name of a dimension by meaning

SELECT api_name, ui_name
FROM ga4.main.dimensions('0')
WHERE description ILIKE '%landing page%';
5 more examples

Who is on the site right now, by country

SELECT property_id, country, activeUsers
FROM ga4.main.realtime_report('', dimensions => ['country'], metrics => ['activeUsers'])
ORDER BY activeUsers DESC;

Custom dimensions across every property

SELECT property_id, api_name, display_name
FROM ga4.main.custom_dimensions('')
ORDER BY property_id, api_name;

Revenue and revenue per session over the last 28 days for each property, with the currency that property reports revenue in

SELECT p.display_name, p.currency_code, r.sessions,
  round(r.totalRevenue, 2) AS revenue,
  round(r.totalRevenue / nullif(r.sessions, 0), 2) AS revenue_per_session
FROM ga4.main.report('', metrics => ['sessions', 'totalRevenue']) r
JOIN ga4.main.properties p USING (property_id)
ORDER BY revenue DESC, p.display_name;

How many times each key event (conversion) fired in each property over the last 28 days

SELECT r.property_id, k.event_name, k.counting_method, r.eventCount
FROM ga4.main.report('', dimensions => ['eventName'], metrics => ['eventCount']) r
JOIN ga4.main.key_events('') k ON k.property_id = r.property_id AND k.event_name = r.eventName
ORDER BY r.property_id, r.eventCount DESC, k.event_name;

Which account and property each website measurement id (G-...) reports into

SELECT d.measurement_id, d.default_uri, s.account_name, s.property_name,
  d.property_id
FROM ga4.main.data_streams('') d
JOIN ga4.main.account_summaries s USING (property_id)
WHERE d.type = 'WEB_DATA_STREAM'
ORDER BY s.account_name, s.property_name, d.measurement_id;
Tables
account_summaries 2 examples6 cols

Every readable GA4 property with its account β€” the entry point

Columns
account_idnot null VARCHAR
Numeric Google Analytics account id.
account_name VARCHAR
Display name of the account.
property_id VARCHAR
Numeric GA4 property id β€” the first argument every report and per-property function takes. NULL for an account the credential can see but that has no property it can read.
property_name VARCHAR
Display name of the property.
property_type VARCHAR
PROPERTY_TYPE_ORDINARY, PROPERTY_TYPE_SUBPROPERTY or PROPERTY_TYPE_ROLLUP.
parent VARCHAR
Resource name of the property's parent: 'accounts/…' for an ordinary property, 'properties/…' for a subproperty.
ConstraintsUNIQUE (account_id, property_id) Β· FOREIGN KEY (account_id) REFERENCES accounts(account_id) Β· FOREIGN KEY (property_id) REFERENCES properties(property_id)
Examples (2)

Every property this credential can read

SELECT account_name, property_id, property_name
FROM ga4.main.account_summaries
ORDER BY account_name, property_name;

Properties per account

SELECT account_name, count(property_id) AS properties
FROM ga4.main.account_summaries
GROUP BY account_name
ORDER BY properties DESC;
Link
accounts 2 examples6 cols

Every readable Google Analytics account

Columns
account_idnot null VARCHAR
Numeric Google Analytics account id.
display_name VARCHAR
Display name of the account.
region_code VARCHAR
Country of the business, as a CLDR region code (e.g. 'US').
create_time TIMESTAMP WITH TIME ZONE
When the account was created.
update_time TIMESTAMP WITH TIME ZONE
When the account's settings were last changed.
gmp_organization VARCHAR
Google Marketing Platform organization resource the account belongs to, if any.
ConstraintsPRIMARY KEY (account_id)
Examples (2)

Accounts by creation date

SELECT account_id, display_name, create_time
FROM ga4.main.accounts
ORDER BY create_time;

Accounts by region

SELECT region_code, count(*) AS accounts
FROM ga4.main.accounts
GROUP BY region_code;
Link
properties 2 examples11 cols

Every readable GA4 property with its time zone, currency and service level

Columns
property_idnot null VARCHAR
Numeric GA4 property id β€” the first argument every report and per-property function takes.
account_idnot null VARCHAR
Account the property belongs to.
display_name VARCHAR
Display name of the property.
property_type VARCHAR
PROPERTY_TYPE_ORDINARY, PROPERTY_TYPE_SUBPROPERTY or PROPERTY_TYPE_ROLLUP.
parent VARCHAR
Resource name of the property's parent account or property.
time_zone VARCHAR
Reporting time zone (IANA, e.g. 'America/New_York'). Report dates and hours are in this zone.
currency_code VARCHAR
ISO 4217 reporting currency; currency metrics are in this unless a report overrides it.
industry_category VARCHAR
Industry the property was categorised under at setup.
service_level VARCHAR
GOOGLE_ANALYTICS_STANDARD or GOOGLE_ANALYTICS_360 β€” which sets the API quota.
create_time TIMESTAMP WITH TIME ZONE
When the property was created.
update_time TIMESTAMP WITH TIME ZONE
When the property's settings were last changed.
ConstraintsPRIMARY KEY (property_id) Β· FOREIGN KEY (account_id) REFERENCES accounts(account_id)
Examples (2)

Properties with their time zone and currency

SELECT property_id, display_name, time_zone, currency_code
FROM ga4.main.properties
ORDER BY display_name;

GA4 360 properties

SELECT property_id, display_name
FROM ga4.main.properties
WHERE service_level = 'GOOGLE_ANALYTICS_360';
Link
Table functions
all_account_summaries () 1 example

Every readable account and property (the scan backing account_summaries)

No arguments
Returns columns
account_id VARCHAR
Numeric Google Analytics account id.
account_name VARCHAR
Display name of the account.
property_id VARCHAR
Numeric GA4 property id β€” the first argument every report and per-property function takes. NULL for an account the credential can see but that has no property it can read.
property_name VARCHAR
Display name of the property.
property_type VARCHAR
PROPERTY_TYPE_ORDINARY, PROPERTY_TYPE_SUBPROPERTY or PROPERTY_TYPE_ROLLUP.
parent VARCHAR
Resource name of the property's parent: 'accounts/…' for an ordinary property, 'properties/…' for a subproperty.
Example

Every readable property, by account

SELECT account_name, property_id, property_name
FROM ga4.main.all_account_summaries()
ORDER BY account_name, property_name;
Link
all_accounts () 1 example

Every readable Google Analytics account (the scan backing accounts)

No arguments
Returns columns
account_id VARCHAR
Numeric Google Analytics account id.
display_name VARCHAR
Display name of the account.
region_code VARCHAR
Country of the business, as a CLDR region code (e.g. 'US').
create_time TIMESTAMP WITH TIME ZONE
When the account was created.
update_time TIMESTAMP WITH TIME ZONE
When the account's settings were last changed.
gmp_organization VARCHAR
Google Marketing Platform organization resource the account belongs to, if any.
Example

Accounts and when they were created

SELECT account_id, display_name, region_code, create_time
FROM ga4.main.all_accounts()
ORDER BY create_time;
Link
all_properties () 1 example

Every readable GA4 property with its settings (the scan backing properties)

No arguments
Returns columns
property_id VARCHAR
Numeric GA4 property id β€” the first argument every report and per-property function takes.
account_id VARCHAR
Account the property belongs to.
display_name VARCHAR
Display name of the property.
property_type VARCHAR
PROPERTY_TYPE_ORDINARY, PROPERTY_TYPE_SUBPROPERTY or PROPERTY_TYPE_ROLLUP.
parent VARCHAR
Resource name of the property's parent account or property.
time_zone VARCHAR
Reporting time zone (IANA, e.g. 'America/New_York'). Report dates and hours are in this zone.
currency_code VARCHAR
ISO 4217 reporting currency; currency metrics are in this unless a report overrides it.
industry_category VARCHAR
Industry the property was categorised under at setup.
service_level VARCHAR
GOOGLE_ANALYTICS_STANDARD or GOOGLE_ANALYTICS_360 β€” which sets the API quota.
create_time TIMESTAMP WITH TIME ZONE
When the property was created.
update_time TIMESTAMP WITH TIME ZONE
When the property's settings were last changed.
Example

Properties with their reporting time zone and currency

SELECT property_id, display_name, time_zone, currency_code
FROM ga4.main.all_properties()
ORDER BY display_name;
Link
check_compatibility (property VARCHAR, dimension_filter := VARCHAR, dimensions := VARCHAR[], metric_filter := VARCHAR, metrics := VARCHAR[]) 2 examples

Which dimensions and metrics can be combined with the ones given

Positional arguments
property VARCHAR
GA4 property id, e.g. '123456789'; '' checks every readable property.
Named arguments
dimension_filter := VARCHAR
FilterExpression JSON the report would use. Β· default ""
dimensions := VARCHAR[]
Dimensions you intend to report on. Β· default []
metric_filter := VARCHAR
Metric FilterExpression JSON the report would use. Β· default ""
metrics := VARCHAR[]
Metrics you intend to report on. Β· default []
Returns columns
property_id VARCHAR
Property the compatibility was checked against.
kind VARCHAR
'dimension' or 'metric'.
api_name VARCHAR
Dimension or metric name.
ui_name VARCHAR
Name shown in the GA4 interface.
compatibility VARCHAR
COMPATIBLE if it can be added to a report with the requested fields, else INCOMPATIBLE.
requested BOOLEAN
Whether this field was one of those passed in.
Examples (2)

Is the requested combination valid?

SELECT property_id, api_name, compatibility
FROM ga4.main.check_compatibility('', dimensions => ['itemName'], metrics => ['sessions'])
WHERE requested
ORDER BY property_id, api_name;

Which dimensions can break down item revenue?

SELECT DISTINCT api_name
FROM ga4.main.check_compatibility('', metrics => ['itemRevenue'])
WHERE kind = 'dimension' AND compatibility = 'COMPATIBLE'
ORDER BY api_name;
Link
custom_dimensions (property VARCHAR) 2 examples

Custom dimensions defined on a GA4 property, with their report api names

Arguments
property VARCHAR
GA4 property id, e.g. '123456789' (or 'properties/123456789'). Empty string = every property the credential can read.
Returns columns
property_id VARCHAR
Property the custom dimension is defined on.
api_name VARCHAR
The name to pass in report(dimensions => [...]): 'customEvent:<parameter>', 'customUser:<parameter>' or 'customItem:<parameter>' depending on scope.
parameter_name VARCHAR
Event, user-property or item parameter the dimension reads.
display_name VARCHAR
Name shown in the GA4 interface.
description VARCHAR
Free-text description entered by whoever created it.
scope VARCHAR
EVENT, USER or ITEM.
disallow_ads_personalization BOOLEAN
Whether the dimension is excluded from ads personalization (user scope only).
Examples (2)

Custom dimensions of every property, as report api names

SELECT property_id, api_name, display_name, scope
FROM ga4.main.custom_dimensions('')
ORDER BY property_id, api_name;

Custom dimensions defined on some properties but not others

SELECT api_name, count(*) AS properties
FROM ga4.main.custom_dimensions('')
GROUP BY api_name
ORDER BY properties;
Link
custom_metrics (property VARCHAR) 1 example

Custom metrics defined on a GA4 property, with their report api names

Arguments
property VARCHAR
GA4 property id, e.g. '123456789' (or 'properties/123456789'). Empty string = every property the credential can read.
Returns columns
property_id VARCHAR
Property the custom metric is defined on.
api_name VARCHAR
The name to pass in report(metrics => [...]): 'customEvent:<parameter>'.
parameter_name VARCHAR
Event parameter the metric sums.
display_name VARCHAR
Name shown in the GA4 interface.
description VARCHAR
Free-text description entered by whoever created it.
measurement_unit VARCHAR
STANDARD, CURRENCY, FEET, METERS, KILOMETERS, MILES, MILLISECONDS, SECONDS, MINUTES or HOURS.
scope VARCHAR
Always EVENT for custom metrics.
restricted_metric_types VARCHAR[]
COST_DATA and/or REVENUE_DATA when the metric is hidden from users without that access.
Example

Custom metrics of every property, with their units

SELECT property_id, api_name, display_name, measurement_unit
FROM ga4.main.custom_metrics('')
ORDER BY property_id, api_name;
Link
data_streams (property VARCHAR) 3 examples

Web and app data streams sending data to a GA4 property

Arguments
property VARCHAR
GA4 property id, e.g. '123456789' (or 'properties/123456789'). Empty string = every property the credential can read.
Returns columns
property_id VARCHAR
Property the stream sends data to.
stream_id VARCHAR
Numeric data stream id.
type VARCHAR
WEB_DATA_STREAM, ANDROID_APP_DATA_STREAM or IOS_APP_DATA_STREAM.
display_name VARCHAR
Display name of the stream.
measurement_id VARCHAR
The 'G-XXXXXXX' tag id a website sends hits with (web streams only). Not a property id.
default_uri VARCHAR
Domain of the website the stream measures (web streams only).
firebase_app_id VARCHAR
Firebase app id linked to the stream, if any.
package_name VARCHAR
Android package name (Android streams only).
bundle_id VARCHAR
Apple bundle id (iOS streams only).
create_time TIMESTAMP WITH TIME ZONE
When the stream was created.
update_time TIMESTAMP WITH TIME ZONE
When the stream was last changed.
Examples (3)

Which property does each website measurement id belong to?

SELECT measurement_id, default_uri, property_id
FROM ga4.main.data_streams('')
WHERE type = 'WEB_DATA_STREAM'
ORDER BY default_uri;

Every stream, grouped by property

SELECT property_id, stream_id, type, display_name
FROM ga4.main.data_streams('')
ORDER BY property_id, stream_id;

Which account and property each website measurement id (G-...) reports into

SELECT d.measurement_id, d.default_uri, s.account_name, s.property_name,
  d.property_id
FROM ga4.main.data_streams('') d
JOIN ga4.main.account_summaries s USING (property_id)
WHERE d.type = 'WEB_DATA_STREAM'
ORDER BY s.account_name, s.property_name, d.measurement_id;
Link
dimensions (property VARCHAR) 3 examples

Every dimension report() accepts for a property, custom ones included

Arguments
property VARCHAR
GA4 property id; '0' or '' for the universal set shared by every property.
Returns columns
property_id VARCHAR
Property the list was fetched for ('0' = the universal set).
api_name VARCHAR
Name to pass in report(dimensions => [...]); also the result column's name.
ui_name VARCHAR
Name shown in the GA4 interface.
description VARCHAR
Google's description of the dimension.
category VARCHAR
Grouping in the GA4 interface, e.g. 'Geography' or 'Traffic source'.
custom_definition BOOLEAN
True for a property's own custom dimension.
column_type VARCHAR
SQL type the column gets in report(): DATE for date/firstSessionDate, TIMESTAMP for dateHour/dateHourMinute, otherwise VARCHAR.
deprecated_api_names VARCHAR[]
Older names still accepted for this dimension.
Examples (3)

Traffic-source dimensions

SELECT api_name, ui_name, description
FROM ga4.main.dimensions('0')
WHERE category = 'Traffic source'
ORDER BY api_name;

Find a dimension by what it means

SELECT api_name, ui_name
FROM ga4.main.dimensions('0')
WHERE description ILIKE '%landing page%';

Dimensions that are new names for a deprecated one

SELECT api_name, deprecated_api_names
FROM ga4.main.dimensions('0')
WHERE len(deprecated_api_names) > 0;
Link
key_events (property VARCHAR) 3 examples

Events a GA4 property counts as key events (formerly conversions)

Arguments
property VARCHAR
GA4 property id, e.g. '123456789' (or 'properties/123456789'). Empty string = every property the credential can read.
Returns columns
property_id VARCHAR
Property the key event is configured on.
event_name VARCHAR
Event name marked as a key event (formerly 'conversion'); filter reports on it with the eventName dimension.
counting_method VARCHAR
ONCE_PER_EVENT or ONCE_PER_SESSION β€” how keyEvents counts repeats.
custom BOOLEAN
False for key events Google created automatically (e.g. purchase).
deletable BOOLEAN
Whether the key event can be removed.
default_value DOUBLE
Default monetary value assigned when the event carries none.
default_currency_code VARCHAR
Currency of default_value.
create_time TIMESTAMP WITH TIME ZONE
When the event was marked as a key event.
Examples (3)

Key events of every property

SELECT property_id, event_name, counting_method, custom
FROM ga4.main.key_events('')
ORDER BY property_id, event_name;

Properties that do not track a purchase key event

SELECT s.property_id, s.property_name
FROM ga4.main.account_summaries s
WHERE s.property_id IS NOT NULL AND s.property_id NOT IN (SELECT property_id FROM ga4.main.key_events('') WHERE event_name = 'purchase');

How many times each key event (conversion) fired in each property over the last 28 days

SELECT r.property_id, k.event_name, k.counting_method, r.eventCount
FROM ga4.main.report('', dimensions => ['eventName'], metrics => ['eventCount']) r
JOIN ga4.main.key_events('') k ON k.property_id = r.property_id AND k.event_name = r.eventName
ORDER BY r.property_id, r.eventCount DESC, k.event_name;
Link
metrics (property VARCHAR) 2 examples

Every metric report() accepts for a property, custom ones included

Arguments
property VARCHAR
GA4 property id; '0' or '' for the universal set shared by every property.
Returns columns
property_id VARCHAR
Property the list was fetched for ('0' = the universal set).
api_name VARCHAR
Name to pass in report(metrics => [...]); also the result column's name.
ui_name VARCHAR
Name shown in the GA4 interface.
description VARCHAR
Google's description of the metric.
category VARCHAR
Grouping in the GA4 interface, e.g. 'User' or 'Ecommerce'.
type VARCHAR
Google's metric type: TYPE_INTEGER, TYPE_FLOAT, TYPE_SECONDS, TYPE_CURRENCY, ….
column_type VARCHAR
SQL type the column gets in report(): BIGINT for TYPE_INTEGER, otherwise DOUBLE.
expression VARCHAR
Formula for a derived metric, e.g. 'sessions / totalUsers'.
custom_definition BOOLEAN
True for a property's own custom or calculated metric.
blocked_reasons VARCHAR[]
NO_REVENUE_METRICS / NO_COST_METRICS when this credential cannot see the metric's values.
deprecated_api_names VARCHAR[]
Older names still accepted for this metric.
Examples (2)

Ecommerce metrics and their types

SELECT api_name, ui_name, type
FROM ga4.main.metrics('0')
WHERE category = 'Ecommerce'
ORDER BY api_name;

Derived metrics and how they are computed

SELECT api_name, expression
FROM ga4.main.metrics('0')
WHERE expression IS NOT NULL AND expression <> ''
ORDER BY api_name;
Link
property_quota (property VARCHAR) 1 example

Remaining Data API quota (tokens per hour/day, concurrency) for a property

Arguments
property VARCHAR
GA4 property id, e.g. '123456789'; '' reads every readable property's quota.
Returns columns
property_id VARCHAR
Property the quota belongs to.
quota VARCHAR
tokensPerDay, tokensPerHour, tokensPerProjectPerHour, concurrentRequests, serverErrorsPerProjectPerHour or potentiallyThresholdedRequestsPerHour.
consumed BIGINT
Amount used by the probe request that read this.
remaining BIGINT
Amount left in the current window after that request.
description VARCHAR
What the quota limits and when it resets.
Example

Tokens left this hour and today, per property

SELECT property_id, quota, remaining
FROM ga4.main.property_quota('')
WHERE quota IN ('tokensPerHour', 'tokensPerDay')
ORDER BY property_id, quota;
Link
realtime_report (property VARCHAR, dimension_filter := VARCHAR, dimensions := VARCHAR[], max_rows := BIGINT, metric_filter := VARCHAR, metrics := VARCHAR[], minutes_ago_end := BIGINT, minutes_ago_start := BIGINT) 2 examples

Run a GA4 realtime report over the last 30 minutes

Positional arguments
property VARCHAR
GA4 property id, e.g. '123456789'; '' runs the report on every readable property.
Named arguments
dimension_filter := VARCHAR
GA4 FilterExpression JSON on dimensions. Β· default ""
dimensions := VARCHAR[]
Realtime dimension api names to group by (the realtime schema, not report()'s); see the function docs. Β· default []
max_rows := BIGINT
Row limit (0 = the API maximum of 250,000). Β· default 0
metric_filter := VARCHAR
GA4 FilterExpression JSON on metrics. Β· default ""
metrics := VARCHAR[]
Realtime metric api names to aggregate; the function docs list the realtime set. Β· default []
minutes_ago_end := BIGINT
Window end, in minutes before now (0 = now). Β· default 0
minutes_ago_start := BIGINT
Window start, in minutes before now; standard properties allow up to 29, GA4 360 up to 59. Β· default 29
Returns columns
property_id VARCHAR
Property the row belongs to.
minutesAgo BIGINT
Minutes before now; 0 is the current minute.
any other dimension VARCHAR
The dimension's value, named exactly as requested.
activeUsers, eventCount, keyEvents, screenPageViews BIGINT
Counts in the window.
any other metric DOUBLE
The metric's value.
Returns columns Β· depends on the arguments
Always first
property_id VARCHAR
Property the row belongs to.
One column per requested dimension
minutesAgo BIGINT
Minutes before now; 0 is the current minute.
any other dimension VARCHAR
The dimension's value, named exactly as requested.
One column per requested metric
activeUsers, eventCount, keyEvents, screenPageViews BIGINT
Counts in the window.
any other metric DOUBLE
The metric's value.
Examples (2)

Active users right now, by property and country

SELECT property_id, country, activeUsers
FROM ga4.main.realtime_report('', dimensions => ['country'], metrics => ['activeUsers'])
ORDER BY activeUsers DESC;

Events per minute over the last half hour, per property

SELECT property_id, minutesAgo, eventCount
FROM ga4.main.realtime_report('', dimensions => ['minutesAgo'], metrics => ['eventCount'])
ORDER BY property_id, minutesAgo;
Link
report (property VARCHAR, cache_ttl := BIGINT, compare_end_date := VARCHAR, compare_start_date := VARCHAR, currency_code := VARCHAR, dimension_filter := VARCHAR, dimensions := VARCHAR[], end_date := VARCHAR, keep_empty_rows := BOOLEAN, max_rows := BIGINT, metric_filter := VARCHAR, metrics := VARCHAR[], quality_columns := BOOLEAN, start_date := VARCHAR) 5 examples

Run a GA4 report: dimensions Γ— metrics over a date range

Positional arguments
property VARCHAR
GA4 property id, e.g. '123456789'; '' runs the report on every readable property.
Named arguments
cache_ttl := BIGINT
Seconds DuckDB may reuse this result (0 = always re-query). Β· default 0
compare_end_date := VARCHAR
End of the comparison range, inclusive. Β· default ""
compare_start_date := VARCHAR
Start of a second range to compare against, which adds a dateRange column; empty for no comparison. Β· default ""
currency_code := VARCHAR
ISO 4217 code for currency metrics; default is the property's. Β· default ""
dimension_filter := VARCHAR
GA4 FilterExpression JSON applied before aggregation; may reference dimensions that are not in the output. Β· default ""
dimensions := VARCHAR[]
Dimension api names to group by, each becoming a column; search dimensions(property) for valid names. Β· default []
end_date := VARCHAR
Last day of the range, inclusive, in the property's time zone β€” a GA4 date: an ISO date, today, yesterday, or NdaysAgo (such as 28daysAgo). Β· default "yesterday"
keep_empty_rows := BOOLEAN
Also return rows whose metrics are all zero. Β· default false
max_rows := BIGINT
Stop after this many rows (0 = every row the report has). Β· default 0
metric_filter := VARCHAR
GA4 FilterExpression JSON on metrics, applied after aggregation. Β· default ""
metrics := VARCHAR[]
Metric api names to aggregate, each becoming a column; search metrics(property). Β· default []
quality_columns := BOOLEAN
Append subject_to_thresholding, data_loss_from_other_row and sampling_ratio. Β· default false
start_date := VARCHAR
First day of the range, inclusive β€” a GA4 date: an ISO date, today, yesterday, or NdaysAgo (such as 28daysAgo). Β· default "28daysAgo"
Returns columns
property_id VARCHAR
Property the row belongs to.
date`, `firstSessionDate DATE
Calendar day in the property's time zone.
dateHour`, `dateHourMinute TIMESTAMP
Wall-clock time in the property's time zone.
any other dimension VARCHAR
The dimension's value, named exactly as requested.
dateRange VARCHAR
`current` or `comparison`.
integer metric (`TYPE_INTEGER`) BIGINT
Counts such as activeUsers or sessions.
any other metric DOUBLE
Rates, durations, currency and distances.
subject_to_thresholding BOOLEAN
GA4 withheld rows for privacy.
data_loss_from_other_row BOOLEAN
Rare values were folded into an (other) row.
sampling_ratio DOUBLE
Share of events used; 1.0 when unsampled.
Returns columns Β· depends on the arguments
Always first
property_id VARCHAR
Property the row belongs to.
One column per requested dimension
date`, `firstSessionDate DATE
Calendar day in the property's time zone.
dateHour`, `dateHourMinute TIMESTAMP
Wall-clock time in the property's time zone.
any other dimension VARCHAR
The dimension's value, named exactly as requested.
When a comparison range is given
dateRange VARCHAR
`current` or `comparison`.
One column per requested metric
integer metric (`TYPE_INTEGER`) BIGINT
Counts such as activeUsers or sessions.
any other metric DOUBLE
Rates, durations, currency and distances.
With `quality_columns => true`
subject_to_thresholding BOOLEAN
GA4 withheld rows for privacy.
data_loss_from_other_row BOOLEAN
Rare values were folded into an (other) row.
sampling_ratio DOUBLE
Share of events used; 1.0 when unsampled.
Examples (5)

Daily active users and sessions over the last 28 days, per property

SELECT property_id, date, activeUsers, sessions
FROM ga4.main.report('', dimensions => ['date'], metrics => ['activeUsers', 'sessions'])
ORDER BY property_id, date;

Sessions and key events by channel, per property

SELECT property_id, sessionDefaultChannelGroup, sessions, keyEvents
FROM ga4.main.report('', dimensions => ['sessionDefaultChannelGroup'], metrics => ['sessions', 'keyEvents'])
ORDER BY property_id, sessions DESC;

Top pages last week against the week before

SELECT property_id, pagePath, dateRange, screenPageViews
FROM ga4.main.report('', dimensions => ['pagePath'], metrics => ['screenPageViews'], start_date => '7daysAgo', end_date => 'yesterday', compare_start_date => '14daysAgo', compare_end_date => '8daysAgo')
ORDER BY screenPageViews DESC
LIMIT 20;
2 more examples

Purchase events by country, filtering on a dimension that is not a column

SELECT property_id, country, eventCount
FROM ga4.main.report('', dimensions => ['country'], metrics => ['eventCount'], dimension_filter => '{"filter": {"fieldName": "eventName", "stringFilter": {"value": "purchase"}}}')
ORDER BY eventCount DESC;

Revenue and revenue per session over the last 28 days for each property, with the currency that property reports revenue in

SELECT p.display_name, p.currency_code, r.sessions,
  round(r.totalRevenue, 2) AS revenue,
  round(r.totalRevenue / nullif(r.sessions, 0), 2) AS revenue_per_session
FROM ga4.main.report('', metrics => ['sessions', 'totalRevenue']) r
JOIN ga4.main.properties p USING (property_id)
ORDER BY revenue DESC, p.display_name;
Link

Credentials

The secret type ga4 declares, as reported by the worker itself.

google_analytics

How to get these credentials

Google Analytics credentials (scope analytics.readonly). Provide ONE of: service_account_json (a service-account key, the account added to the GA4 property as a Viewer); client_id + client_secret + refresh_token (an OAuth user grant); or access_token (short-lived). quota_project_id optionally bills API quota to a specific Google Cloud project.

secret.sql
CREATE SECRET google_analytics (
    TYPE google_analytics,
    service_account_json '<GOOGLE_ANALYTICS_SERVICE_ACCOUNT_JSON>',  -- secret
    client_id            '<client_id>',
    client_secret        '<GOOGLE_ANALYTICS_CLIENT_SECRET>',  -- secret
    refresh_token        '<REFRESH_TOKEN>',  -- secret
    access_token         '<ACCESS_TOKEN>',  -- secret
    quota_project_id     '<quota_project_id>'
);
Key Type Required Description
service_account_json secret VARCHAR β€” Contents of a service-account JSON key file.
client_id VARCHAR β€” OAuth client id of a user grant.
client_secret secret VARCHAR β€” OAuth client secret of a user grant.
refresh_token secret VARCHAR β€” OAuth refresh token granting analytics.readonly.
access_token secret VARCHAR β€” Short-lived OAuth access token (about an hour).
quota_project_id VARCHAR β€” Google Cloud project to bill API quota to (optional).

The worker doesn't mark which keys are required.

Needed by all_account_summariesall_accountsall_propertiesdata_streamscustom_dimensionscustom_metricskey_eventsdimensionsmetricscheck_compatibilityproperty_quotareport and 1 more functions

Create the secret in the same session, after attaching ga4 β€” the worker registers its secret types at ATTACH. Keys marked secret are masked in duckdb_secrets(); angle-bracket values are placeholders. Read credentials from your environment or secret store in your application and pass them through your SQL client’s parameter bindings. Keep real values out of saved SQL and history. Native DuckDB and Haybarn do not provide a SQL getenv() function.

Try these queries

summaries_and_scan_function_agree β€” The account_summaries table and the function behind it return the same rows.

SELECT (SELECT count(*) FROM ga4.main.account_summaries) = (SELECT count(*) FROM ga4.main.all_account_summaries());

Uses account_summariesall_account_summaries

universal_metadata_is_populated β€” The universal dimension list includes the date dimension, typed DATE.

SELECT column_type FROM ga4.main.dimensions('0') WHERE api_name = 'date';

Uses dimensions

integer_metrics_are_bigint β€” activeUsers is declared TYPE_INTEGER and so becomes BIGINT.

SELECT column_type
FROM ga4.main.metrics('0')
WHERE api_name = 'activeUsers';

Uses metrics

report_columns_are_typed β€” A report's date column is a DATE and its count metric a BIGINT.

SELECT typeof(date), typeof(activeUsers)
FROM ga4.main.report('', dimensions => ['date'], metrics => ['activeUsers'], keep_empty_rows => true)
LIMIT 1;

Uses report

Who is on the site right now, by country

SELECT property_id, country, activeUsers
FROM ga4.main.realtime_report('', dimensions => ['country'], metrics => ['activeUsers'])
ORDER BY activeUsers DESC

Uses realtime_report

Custom dimensions across every property

SELECT property_id, api_name, display_name
FROM ga4.main.custom_dimensions('')
ORDER BY property_id, api_name

Uses custom_dimensions

1 more example

a_report_respects_max_rows β€” max_rows caps the rows a report returns.

SELECT count(*) <= 3
FROM ga4.main.report('', dimensions => ['date'], metrics => ['activeUsers'], max_rows => 3);

Uses report

31 more examples in the Catalog, each listed under the table or function it uses.

Questions it can answer

Plain-English questions from the worker's agent test tasks. An AI agent with this catalog attached should answer each one with SQL.

  • Which Google Analytics properties can I query? Give their ids and names.
  • How many active users did my first GA4 property have on each of the last 7 days?
  • How many distinct users visited my first GA4 property in the last 28 days?
  • Which marketing channels drove the most sessions to my first property last month?
  • In my first property, how many purchase events came from each country in the last 28 days?
  • What is the GA4 api name for the landing page dimension?

Google Analytics is an independent open-source connector from Query.Farm. It is not affiliated with, endorsed by or sponsored by the services, projects or organisations it works with. Product names, logos and trademarks belong to their respective owners.