We’re back with another article in our series of BigQuery AI function examples. BigQuery’s AI.AGG is an aggregate function. You call it the same way you’d call SUM or COUNT, in a SELECT with a GROUP BY. The difference is what it does with each group: instead of adding up numbers, it reads every row of text (or images, PDFs, audio, video) in that group and answers a question you write in plain English, one answer per group.
Why not just use AI.GENERATE
BigQuery already has general-purpose AI functions, AI.GENERATE and AI.GENERATE_TEXT, that can read a row and return a response. Google’s own documentation recommends AI.AGG for aggregation specifically for two reasons. Firstly, AI.AGG handles the batching for you. If a group has more rows than fit in one model call, it splits them into batches, summarises each batch, then summarises those summaries into a final answer without the need for you to write the logic yourself. Secondly, AI.AGG returns one result per group. AI.GENERATE returns one result per row, which for 50,000 reviews is 50,000 responses, not the one answer per product you might actually want.
The dataset
This article uses the same shared dataset as the rest of this series, which is our synthetic e-commerce orders table, with one addition. AI.AGG needs free text to work on, and the original table is all numbers and categories, so we added a customer_note column: a short, optional note left on each order, varied by product category, with about 40% of orders left blank (NULL), the way most orders never get a comment in real life. The full setup, including the exact SQL to add this column to your own copy of the table, or if you’re setting up for the first time, is in our dataset setup guide. You’ll need bq_ai_demo.ecommerce_orders loaded with that column added before running the queries below. If you have already implemented the dataset, see the instructions in BigQuery Working Examples Dataset Update.
We’ve added a pattern into the notes on purpose. Electronics orders have a recurring, specific complaint: the companion app losing its Bluetooth connection. It shows up in roughly a third of the Electronics notes that exist. It’s there so this article has something real to go looking for, the same way earlier articles in this series planted a tracking fault for AI.KEY_DRIVERS to find.
Syntax
AI.AGG(
[ DISTINCT ]
INPUT,
INSTRUCTION
[, connection_id => 'CONNECTION']
[, endpoint => 'ENDPOINT']
[, max_error_ratio => MAX_ERROR_RATIO]
[, output_schema => 'OUTPUT_SCHEMA']
)
INPUT is the data to summarise. It can be a plain string column, or a STRUCT combining several columns and even references to files in Cloud Storage (images, PDFs, audio, video). INSTRUCTION is the natural-language prompt. connection_id and endpoint control which Vertex AI connection and Gemini model handle the call, more on both below. max_error_ratio and output_schema are covered in their own sections further down.
A basic summary grouped by category
This is a pretty standard use case for those working with VOC tools: group feedback by product and ask what customers are complaining about most.
SELECT
product_category,
COUNT(*) AS order_count,
AI.AGG(
customer_note,
'These are customer notes left on orders for this product category. What are customers complaining about most? If most notes are positive or have no issues, say so plainly instead of inventing a problem.'
) AS feedback_summary
FROM `bq_ai_demo.ecommerce_orders`
GROUP BY product_category
ORDER BY order_count DESC;
We asked the model explicitly for permission to say nothing’s wrong, the same instruction Google’s own blog post uses for its log-analysis example. Without it, a model asked “what are customers complaining about” will often find something to say even when the honest answer is “not much,” because that’s the question it was asked, not because that’s what the data shows.
customer_note is a plain string column here, so any order with no note is simply skipped, it isn’t counted as “no comment,” it just doesn’t contribute to the summary. That’s AI.AGG’s default NULL handling for a single-column input, and for this query it’s the right behaviour: an order with no note has nothing to say.
Expect the Electronics row’s summary to mention the Bluetooth pairing issue, since it’s a real, repeated pattern across roughly a third of that category’s notes. The other categories should come back closer to “mixed, mostly positive, a few isolated complaints,” since nothing comparable is built into their notes. AI.AGG output is nondeterministic, the exact wording will differ if you run this twice, and Google’s own documentation is upfront about that. Run it yourself and check that the pattern, not the exact sentence, lines up with what’s above.

Grouping by a different dimension, and a NULL trap worth knowing about
The same notes can be grouped by device_category instead, to see whether feedback differs by how people ordered. This version has a genuine flaw in it, left in deliberately:
-- Don't copy this one as-is, see below.
SELECT
device_category,
COUNT(*) AS order_count,
AI.AGG(
(STRUCT('Product: ', product_category, ' - Note: ', customer_note)),
'These are customer notes on orders, grouped by the device used to order. Summarise what customers are saying.'
) AS note_summary
FROM `bq_ai_demo.ecommerce_orders`
GROUP BY device_category;
COUNT(*) here still counts every order in each device group. The AI.AGG call doesn’t. BigQuery’s AI functions concatenate a STRUCT’s fields the way CONCAT() does, which means if even one field in the STRUCT is NULL, the whole row is treated as NULL and skipped. Here, every order with no note has its product_category thrown away too, not just the missing note, because we wrapped both fields together in one STRUCT. Roughly 40% of each device group silently disappears from the summary, and nothing in the output tells you that happened.
The fix is IFNULL, applied to the field that’s actually allowed to be empty:
SELECT
device_category,
COUNT(*) AS order_count,
AI.AGG(
(STRUCT('Product: ', product_category, ' - Note: ', IFNULL(customer_note, 'No comment left.'))),
'These are customer notes on orders, grouped by the device used to order. Summarise what customers are saying. If most orders have no comment, mention that plainly.'
) AS note_summary
FROM `bq_ai_demo.ecommerce_orders`
GROUP BY device_category;
Now every row survives, and the model gets told directly when a row has nothing to say rather than quietly losing it. This is the same lesson Google’s own documentation gives using its own cymbal_pets example, missing product descriptions silently drop the whole row unless you IFNULL them first, it’s just easier to miss here because the thing going missing is a comment, not a whole product record.

Structured output for a pipeline rather than a sentence
A free-text summary is fine to read, however, it isn’t something you can reliably parse downstream. output_schema fixes that by asking for a defined structure instead of a sentence:
SELECT
product_category,
COUNT(*) AS order_count,
AI.AGG(
IFNULL(customer_note, 'No comment left.'),
'These are customer notes left on orders for this product category. Identify the distinct themes in the feedback.',
output_schema => '''
themes ARRAY<STRUCT<
theme STRING NOT NULL,
is_complaint BOOL NOT NULL,
example_note STRING NOT NULL
>>
'''
) AS note_themes
FROM `bq_ai_demo.ecommerce_orders`
GROUP BY product_category
ORDER BY order_count DESC;
With output_schema set, AI.AGG returns a STRUCT matching that schema instead of a plain string, one row per theme per category once you unnest themes. NOT NULL on each field is worth keeping on by default. Google’s documentation recommends it, since without it the model can return NULL for a field instead of a real value, and a NOT NULL field is one less thing to check for downstream.
Worth knowing before you build a pipeline on this: the database engine doesn’t enforce the schema you ask for. AI.AGG always returns a string underneath, Google’s documentation says this plainly, the structure is the model doing its best to follow your schema, not a guarantee from BigQuery that it will.

The group and row limits
Google’s documentation recommends no more than 1,000 distinct groups for good performance. Our dataset only has 5 product categories or 3 device categories, nowhere near that, but it matters the moment you group by something higher-cardinality like a customer ID, a SKU, a day. There are also per-query row caps depending on what kind of data you’re sending: 20 million rows for text and single images, 100,000 for PDFs, 10,000 for audio, 1,000 for video. If you go past these, the query can fail outright or come back with only partial results.
Separately, function output is capped at 10,000 tokens per group. For a short feedback summary that’s generous. For an instruction asking the model to list every distinct issue across a genuinely huge, varied group, it’s a real ceiling.
Handling failures without silently losing results
max_error_ratio sets how much row-level failure the query will tolerate before it fails outright, rather than returning results built from whatever didn’t fail:
SELECT
product_category,
AI.AGG(
customer_note,
'Summarise the main themes in these notes.',
max_error_ratio => 0.05
) AS summary
FROM `bq_ai_demo.ecommerce_orders`
WHERE customer_note IS NOT NULL
GROUP BY product_category;
With this set to 0.05, the query fails if more than 5% of rows fail inference (a quota hit, a model error, invalid input), instead of quietly handing back a summary built from whatever’s left. The default is 1.0, meaning almost anything short of total failure gets accepted silently. For a one-off exploration that’s fine, but for a report someone’s going to read as the finished answer, picking a real threshold is worth doing deliberately rather than leaving the default in place by accident.
One subtlety worth knowing if you combine this with LIMIT: the error ratio is calculated on the rows the model actually processed, before the LIMIT is applied, not on the rows that make it into your final output. A batch can have a 15% failure rate, comfortably under a 20% threshold, and still leave your visible output looking far worse than that if the failed rows happen to be among the ones your LIMIT kept.
Managing cost: batching, and the JOIN/LIMIT trap
AI.AGG is genuinely useful because it hides the batching logic from you. That same batching is also why it can cost more than it looks like it should. Because a large group gets split into batches, summarised, then re-summarised, the total number of tokens sent to Gemini can end up higher than the number of tokens actually in your source data, sometimes considerably higher, depending on how many rounds of aggregation a group needs.
Google’s documentation calls out one specific trap directly: a query that uses JOIN or ORDER BY ... LIMIT upstream of an AI function can process more rows than the LIMIT suggests, because of how BigQuery’s query engine processes batches internally. This isn’t a safe way to control cost:
-- Doesn't reliably cap what gets sent to Gemini.
SELECT
product_category,
AI.AGG(
customer_note,
'Summarise the main themes in these notes.'
) AS summary
FROM (
SELECT product_category, customer_note
FROM `bq_ai_demo.ecommerce_orders`
WHERE customer_note IS NOT NULL
ORDER BY order_date DESC
LIMIT 500
)
GROUP BY product_category;
The fix Google recommends is to materialise the exact rows you want into their own table first, then run AI.AGG against that table directly:
CREATE OR REPLACE TABLE `bq_ai_demo.recent_orders_for_review` AS
SELECT product_category, customer_note
FROM `bq_ai_demo.ecommerce_orders`
WHERE customer_note IS NOT NULL
ORDER BY order_date DESC
LIMIT 500;
SELECT
product_category,
AI.AGG(
customer_note,
'Summarise the main themes in these notes.'
) AS summary
FROM `bq_ai_demo.recent_orders_for_review`
GROUP BY product_category;
Before running either version at any real scale, AI.COUNT_TOKENS gives you a cost estimate for free:
SELECT SUM(AI.COUNT_TOKENS(customer_note)) AS estimated_input_tokens
FROM `bq_ai_demo.ecommerce_orders`
WHERE customer_note IS NOT NULL;
Run that before you run AI.AGG on anything larger than a demo table. It’s a one-line check against a function that can quietly multiply your token count without telling you first.
Picking a model
Leave endpoint unset and BigQuery picks a recent Gemini model for you. For anything going into a production pipeline, setting it explicitly is worth doing, since the default can change over time and your prompt’s behaviour with it:
AI.AGG(
customer_note,
'Summarise the main themes in these notes.',
endpoint => 'gemini-3.5-flash'
)
gemini-4-argon, the model behind our recent five-part series on Google’s latest release, is also on the supported list for this function, alongside several Gemini 3.x flash variants. A short model name like this resolves automatically to a regional endpoint based on where your query runs; a fully-qualified endpoint is only needed if you want a specific region or a global endpoint instead.
What this is useful for
The old version of this: export the reviews, read a sample of them, tag them in a spreadsheet, build a pivot table, write a summary nobody reads past the first line. A genuinely tedious week, repeated every time someone wants an update. AI.AGG turns the reading-and-summarising part into one GROUP BY.
It isn’t free, in money or in reliability. The batching that makes it able to handle more rows than fit in a model’s context window is also what can quietly multiply the tokens you’re billed for, nondeterminism means the exact wording changes between runs even on identical data, and a NULL buried inside a STRUCT can drop rows from your summary without any error telling you it happened. None of that makes it not worth using. It makes it worth checking what it actually processed before you present the result as settled.
All articles in this series
Newsletter
Occasional notes on data, tracking & AI-readiness
No spam, no growth-hacking. Just an email when there's something worth reading.