AI functions in BigQuery (AI.GENERATE, AI.IF, AI.CLASSIFY)
Which BigQuery AI function to use, what each returns, what a query really costs and why it returns NULL. Every row is a Gemini call that Vertex AI bills, and the dry run leaves it out.
BigQuery’s AI functions send a prompt to a Gemini model for every row and return the answer as a SQL value. Vertex AI bills those calls per token, on top of the query, and the dry run shows only the bytes of the columns you read.
SELECT title, AI.GENERATE(CONCAT('Summarize in one sentence: ', body)) .result AS summaryFROM `bigquery-public-data.bbc_news.fulltext`
This query will process 4.8 MiB when run.
4.8 MiB is the size of the title and body columns of the BBC news table. The Gemini call for each of its rows isn’t in it. A prompt with no table at all reads nothing:
SELECT AI.GENERATE('Write a haiku about nulls').result AS poemThis query will process 0 B when run.
0 bytes, one Gemini call. In Querylab.io the status bar adds AI calls billed separately to such an estimate, and can price the calls from sample rows before you run (AI function costs).
Pick the function
There are two families. With AI.GENERATE and its typed forms you choose the model, the prompt and the parameters. The managed functions (AI.IF, AI.SCORE, AI.CLASSIFY, AI.AGG) choose the model and wrap your prompt in instructions of their own.
| To… | Use | Returns | Put it in |
|---|---|---|---|
| filter or join on a condition | AI.IF(prompt) | BOOL | WHERE, JOIN ... ON |
| rate rows | AI.SCORE(prompt) | FLOAT64, no fixed range: give one in the prompt | ORDER BY |
| label rows | AI.CLASSIFY(input, categories) | STRING; ARRAY<STRING> once you write output_mode | GROUP BY |
| sum up many rows | AI.AGG(input, instruction) | one STRING per group | an aggregate |
| write free text or extract fields | AI.GENERATE(prompt) | STRUCT<result STRING, full_response JSON, status STRING> | the select list |
| get one typed value | AI.GENERATE_BOOL, _INT, _DOUBLE | the same struct, with a typed result | the select list |
| count tokens before you run | AI.COUNT_TOKENS(prompt) | STRUCT<result INT64, full_response JSON> | the select list |
AI.EMBED makes embeddings and AI.SIMILARITY compares two inputs by them (Vector search). The table functions AI.GENERATE_TEXT, AI.GENERATE_TABLE and the older ML.GENERATE_TEXT need a remote model (BigQuery ML). AI.TRANSLATE, AI.PARSE_DOCUMENT and the other task functions call other Cloud AI APIs instead of Gemini.
Inside the parentheses, the editor lists every argument the function takes:
SELECT AI.CLASSIFY(body, ) FROM warehouse.reviewsClassifies the input into one of the provided categories. Returns a STRING, or an ARRAY<STRING> when output_mode is written. Optimized mode (embeddings, optimization_mode) is GA since 2026-11-17.
Build the prompt from columns
A prompt is a string, or a struct of strings and columns that BigQuery joins together. A struct can also hold ObjectRef values, so the model reads images, audio, video and PDFs from Cloud Storage.
SELECT review_id
FROM mydataset.reviews
WHERE AI.IF(('Is this review a complaint? ', body));
SELECT AI.CLASSIFY(body, ['billing', 'shipping', 'other']) AS topic, COUNT(*) AS n
FROM mydataset.reviews
GROUP BY topic;
SELECT AI.GENERATE(('Extract the product and the problem: ', body),
output_schema => 'product STRING, problem STRING') AS fields
FROM mydataset.reviews;
Typed output. With output_schema the struct holds your fields in place of result, so you can filter and group on them without a CAST. Only INT64, FLOAT64, BOOL, STRING, ARRAY and STRUCT are allowed.
Model and credentials. Without endpoint, AI.GENERATE uses a recent stable Gemini model and the managed functions pick one by cost and quality. Name one to pin it. Without connection_id, the call runs with your own Google account, which needs the roles/aiplatform.user role on the project.
AI.EMBED and AI.SIMILARITY can also run a built-in model with model => instead of endpoint =>: embeddinggemma-300m in both, and embeddinggemma-2 (Preview, for long text and code) in AI.EMBED only. A built-in model runs inside BigQuery, so Vertex AI bills nothing for it. BigQuery bills the slots or bytes, and for embeddinggemma-2 also the input tokens. Querylab.io offers these names after model => and leaves such a call out of the Vertex AI charges in the estimate.
Google’s overview adds an optimized mode for AI.IF and AI.CLASSIFY (Preview) that trains a small model on a sample of your rows and uses it for the rest. It avoids an LLM call for most rows, which cuts tokens and latency on large tables.
Keep the bill down
- Count before you run.
AI.COUNT_TOKENSon a sample of your prompts gives the input tokens, and it bills no Vertex AI charge. The managed functions add 112 to 400 tokens of their own to every call, so a short prompt costs several times what you wrote. - Shrink the input first. With a
JOINorORDER BY ... LIMIT, the model can see more rows than the result has. Google’s advice is to write the rows you want to a table, then call the function on that table.LIMITdoesn’t lower the bytes either (How BigQuery bills a query). - Store the answers. Write them with
CREATE TABLE ... AS SELECTand query that table, so later queries don’t call the model for rows it already answered. - Optimized mode. On
AI.IFandAI.CLASSIFY,optimization_mode => 'MINIMIZE_COST'labels a sample of rows with Gemini, trains a small model on them and answers the rest with it. It needs about 3,000 input rows and embeddings of each row (theembeddingsargument, or a column BigQuery generates). If the small model fails BigQuery’s quality check, the query fails. - Cap it with token quotas. A byte limit doesn’t stop model charges. The daily quotas do: by default
GenAiInputTokensPerDayis 200 billion andGenAiOutputTokensPerDay20 billion per project, with lower per-user quotas. You can request an adjustment to each.
After a run, Job information shows the input, output, thought and cache tokens. The charge appears in Cloud Billing under Vertex AI, with the label bigquery_job_id_prefix, up to 24 hours later.
When rows come back NULL or it fails
NULL rows, no error. A row whose call fails (over quota with RESOURCE_EXHAUSTED, the model unavailable, or for AI.GENERATE a safety filter) returns NULL, and the query still succeeds with a warning under Gen AI function errors in Job information. AI.GENERATE says why in status. The managed functions return a bare value with no status. On AI.IF, AI.CLASSIFY and AI.SCORE, set max_error_ratio to a share between 0.0 and 1.0, say 0.2, and the query fails when more rows than that fail. The default, 1.0, fails only when every row fails. With LIMIT, the visible rows can hold more NULLs than the ratio, because the limit applies after the model has answered a batch. The editor marks a ratio outside the range:
SELECT review_idFROM warehouse.reviewsWHERE AI.IF(('Is this review a complaint? ', body), max_error_ratio => 2)
No matching signature. The function doesn’t take that argument. AI.GENERATE has no max_error_ratio, and AI.SCORE has no optimization_mode or embeddings.
Optimized mode refused. optimization_mode takes MINIMIZE_COST or MAXIMIZE_QUALITY, in any case. output_mode takes single or multi, in lower case. embeddings can’t be a literal array, and max_error_ratio doesn’t work with MINIMIZE_COST. At run time, too few rows or a small model that fails the quality check end the query.
output_schema refused. TIMESTAMP, DATE and BYTES fail with Unsupported field type. Ask for a STRING and parse it.
Permission denied. Without a connection, you need roles/aiplatform.user on the project.
DEDICATED with no Provisioned Throughput. request_type => 'DEDICATED' uses only Provisioned Throughput and returns an invalid query error if you have none. The default uses Provisioned Throughput when you bought it, and shared quota otherwise.
Inside a VPC Service Controls perimeter. An ObjectRef with delegated access, such as the ref column of an object table, writes HTTP links are not supported for requests restricted by VPCSC to status. Pass OBJ.MAKE_REF(uri) instead.