Installation

Install as Agent Plugin Recommended
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install bigquery-ai-ml@skills-hub

Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled). Plugin bigquery-ai-ml v1.0.0 follows the Agent Plugins spec.

Install with the gh extension
gh skills-hub install bigquery-ai-ml

Don't have the extension? Run gh extension install samueltauil/skills-hub first.

Download and extract to your repository:

.github/skills/bigquery-ai-ml/

Extract the ZIP to .github/skills/ in your repo. The folder name must match bigquery-ai-ml for Copilot to auto-discover it.

Skill Files (25)

SKILL.md 8.8 KB
---
name: bigquery-ai-ml
metadata:
  version: "1.1.3"
  category: AiAndMachineLearning
  publisher: google
description: >-
  Leverages BigQuery's built-in machine learning and GenAI capabilities
  for advanced data analytics. Use when you need to write SQL queries
  that perform time-series forecasting, predict values, detect outliers or anomalies, find key drivers,
  perform semantic search or vector search, classify text, calculate similarity,
  summarize content, translate language, evaluate models, filter by semantic conditions,
  measure the causal effect of an intervention, compute correlations between columns,
  generate descriptive statistics and table distribution profiles,
  detect change points or structural breaks, extract trend or seasonality components,
  or leverage generative AI capabilities in BigQuery. Do not use for general
  BigQuery dataset, table, or job management requests.
---

# BigQuery AI & ML

BigQuery integrates with Vertex AI to provide powerful machine learning and
generative AI capabilities directly within SQL queries using built-in functions
like `AI.FORECAST`, `AI.KEY_DRIVERS`, `AI.DETECT_ANOMALIES`, and `AI.GENERATE`.

## Attribution

**MUST READ**: Before executing any `gcloud`, REST API, or MCP command, you
MUST read [Usage Attribution](references/attribution.md). For commands executed
directly in the terminal (never in generated scripts, Terraform, or user code),
prefix `gcloud` with
`CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:bigquery-ai-ml)"`
and append `agent-skills/1.0 (skill:bigquery-ai-ml)` to `User-Agent` headers.

## Function Selection & Reference Directory

Function                      | Reference                                                             | SQL Shape      | Requires `CREATE MODEL` or `CREATE VECTOR INDEX`? | When to Use & Disambiguation
:---------------------------- | :-------------------------------------------------------------------- | :------------- | :------------------------------------------------ | :---------------------------
**`AI.AGG`**                  | [ai_agg.md](references/ai_agg.md)                                     | `Aggregate`    | No                                                | Multi-row semantic aggregation with `GROUP BY`; synthesizes one summary string across many rows (unlike per-row `AI.GENERATE`).
**`AI.CAUSAL_EFFECT`**        | [ai_causal_effect.md](references/ai_causal_effect.md)                 | `TVF`          | No                                                | Quantifies counterfactual post-intervention impact on a time series after a specific treatment timestamp.
**`AI.CLASSIFY`**             | [ai_classify.md](references/ai_classify.md)                           | `Scalar`       | No                                                | Semantic classification of text or multimodal unstructured data into predefined category labels.
**`AI.DETECT_ANOMALIES`**     | [ai_detect_anomalies.md](references/ai_detect_anomalies.md)           | `TVF`          | No                                                | Zero-shot **TimesFM** detector for isolated time-series point anomalies/outliers (use `ML.DETECT_CHANGE_POINTS` for sustained shifts).
**`AI.EVALUATE`**             | [ai_evaluate.md](references/ai_evaluate.md)                           | `TVF`          | No                                                | Zero-shot **TimesFM** time-series forecast evaluation/backtesting against a historical holdout split.
**`AI.FORECAST`**             | [ai_forecast.md](references/ai_forecast.md)                           | `TVF`          | No                                                | Zero-shot **TimesFM** time-series forecasting without training a custom model.
**`AI.GENERATE`**             | [ai_generate.md](references/ai_generate.md)                           | `Scalar`       | No                                                | Default for per-row LLM text or multimodal structured extraction (`output_schema`); returns `STRUCT`. Prefer over `AI.GENERATE_TABLE`.
**`AI.GENERATE_EMBEDDING`**   | [ai_generate_embedding.md](references/ai_generate_embedding.md)       | `TVF`          | Yes                                               | Batch generates `ARRAY<FLOAT64>` vector embeddings for text or visual content using a remote embedding model.
**`AI.GENERATE_TABLE`**       | [ai_generate_table.md](references/ai_generate_table.md)               | `TVF`          | Yes                                               | Table-valued structured extraction (`FROM` clause); only use instead of `AI.GENERATE` when a remote model + TVF is explicitly needed.
**`AI.IF`**                   | [ai_if.md](references/ai_if.md)                                       | `Scalar`       | No                                                | Evaluates boolean semantic conditions (`BOOL`) on text or multimodal data for `WHERE`/`CASE`/`JOIN` filtering (do not use `AI.GENERATE_TABLE`).
**`AI.KEY_DRIVERS`**          | [ai_key_drivers.md](references/ai_key_drivers.md)                     | `TVF`          | No                                                | Default one-step attribution of dimensional segments driving metric changes (`interest_label_col` `TRUE` vs. `FALSE`). Prefer over `CONTRIBUTION_ANALYSIS`.
**`AI.PREDICT`**              | [ai_predict.md](references/ai_predict.md)                             | `TVF`          | No                                                | Zero-shot **TabFM** foundation model for tabular classification or regression without training and managing custom models.
**`AI.SCORE`**                | [ai_score.md](references/ai_score.md)                                 | `Scalar`       | No                                                | Assigns a continuous `FLOAT64` semantic score to text or multimodal data for ranking or sorting (`ORDER BY`).
**`AI.SEARCH`**               | [ai_search.md](references/ai_search.md)                               | `TVF`          | No                                                | Simplified semantic search using a raw string query on tables with autonomous background embeddings (`AI.EMBED` generated column).
**`AI.SIMILARITY`**           | [ai_similarity.md](references/ai_similarity.md)                       | `Scalar`       | No                                                | Computes an on-the-fly semantic similarity score (`FLOAT64`) between two text or multimodal inputs without stored embeddings.
**`Remote Models`**           | [remote_models.md](references/remote_models.md)                       | `CREATE MODEL` | Yes                                               | Creates a Vertex AI `REMOTE WITH CONNECTION DEFAULT` model entity for functions that require one (`AI.GENERATE_TABLE`, `AI.GENERATE_EMBEDDING`, `VECTOR_SEARCH`).
**`CONTRIBUTION_ANALYSIS`**   | [ml_contribution_analysis.md](references/ml_contribution_analysis.md) | `CREATE MODEL` | Yes                                               | Model-based driver analysis (`CREATE MODEL ... OPTIONS(MODEL_TYPE='CONTRIBUTION_ANALYSIS')` + `ML.GET_INSIGHTS`). Use `AI.KEY_DRIVERS` unless a `MODEL` entity is required.
**`ML.CORRELATION`**          | [ml_correlation.md](references/ml_correlation.md)                     | `TVF`          | No                                                | Calculates statistical correlation coefficients between numeric columns, optionally sliced by dimensions.
**`ML.DESCRIBE_DATA`**        | [ml_describe_data.md](references/ml_describe_data.md)                 | `TVF`          | No                                                | Generates descriptive statistics (e.g., count, mean, median, min, max, stddev, quantiles, nulls, top values) for columns in a table or subquery.
**`ML.DETECT_CHANGE_POINTS`** | [ml_detect_change_points.md](references/ml_detect_change_points.md)   | `TVF`          | No                                                | Detects structural breaks or sustained shifts (`[begin_timestamp, end_timestamp]` intervals) in a time series.
**`ML.SEASONALITY`**          | [ml_seasonality.md](references/ml_seasonality.md)                     | `TVF`          | No                                                | Extracts recurring periodic/seasonal components from a historical time series.
**`ML.TREND`**                | [ml_trend.md](references/ml_trend.md)                                 | `TVF`          | No                                                | Extracts the smoothed long-term trend component from a historical time series.
**`VECTOR_SEARCH`**           | [vector_search.md](references/vector_search.md)                       | `TVF`          | Yes                                               | Searches pre-computed `ARRAY<FLOAT64>` embedding columns between a base table and query table (paired with `AI.GENERATE_EMBEDDING`, unlike `AI.SEARCH`).

## Related Skills

-   [BigQuery Basics Skill](../bigquery-basics): SKILL.md file for core BigQuery
    concepts, resource management, CLI, and client libraries.
references/
ai_agg.md 6.0 KB
# BigQuery AI.AGG

`AI.AGG` uses a Vertex AI Gemini model to aggregate data based on natural
language instructions and returns a STRING. It enables reasoning over groups of
rows, up to an entire table.

Common use cases:

-   Sentiment analysis of many user reviews
-   Summarization of content (e.g. log analysis, object table image
    descriptions)
-   Analysis of agent prompts/responses or unstructured feedback
-   Categorization of user feedback, reviews, or support tickets into common
    themes

## Syntax Reference

```sql
AI.AGG(
  [ DISTINCT ]
  input,
  instruction
  [, connection_id => 'CONNECTION_ID']
  [, endpoint => 'ENDPOINT']
  [, output_schema => 'OUTPUT_SCHEMA']
)
```

### Input Arguments

Argument            | Requirement  | Type          | Description
:------------------ | :----------- | :------------ | :----------
**`input`**         | **Required** | String/Struct | The data to be aggregated, as either a `STRING` value or a `STRUCT` object consisting of `STRING` values, [`ObjectRefRuntime` values][objectrefruntime], and arrays of `STRING` and `ObjectRefRuntime` values. `ObjectRefRuntime` values reference text or image data in Cloud Storage and are generated by the [`OBJ.GET_ACCESS_URL` function][obj-get-access-url].
**`instruction`**   | **Required** | String        | The user instruction on how to aggregate data (must be a string literal or query parameter).
**`connection_id`** | Optional     | String        | Identifies a cloud resource connection.
**`endpoint`**      | Optional     | String        | The model endpoint (e.g., `'gemini-2.5-flash'`).
**`output_schema`** | Optional     | String        | Schema of a structured output, as a comma-separated list of fields: `name TYPE [NOT NULL] [OPTIONS(description = '...')]`. Supported types: `STRING`, `INT64`, `FLOAT64`, `BOOL`, `ARRAY`, `STRUCT`. When set, the function returns a `STRUCT` instead of a `STRING`.

### Output Schema

Column Name         | Type     | Description
:------------------ | :------- | :----------
**(Scalar Result)** | `STRING` | The summarized/aggregated result when `output_schema` is not set. If you use the `AI.AGG` function with a `GROUP_BY` statement, then the function returns one value for each input group. Capped at 10000 tokens per group.
**(Struct Result)** | `STRUCT` | Returned instead of `STRING` when `output_schema` is set. Its fields match the specified schema. Capped at 10000 tokens (serialized JSON) per group.

### Using `output_schema`

Use `output_schema` when the user wants structured results (e.g. lists of
topics, counts, scores, labels) that will be filtered, joined, unnested, or
charted downstream, instead of free-form text.

-   Mark fields `NOT NULL` unless the user explicitly allows missing values;
    otherwise the model may return `NULL` for some fields.
-   Add `OPTIONS(description = '...')` to clarify the meaning or format of a
    field (e.g. units, allowed values). `OPTIONS` can be set on `STRUCT`
    subfields too.
-   Use `ARRAY<STRUCT<...>>` for "top N" or list-style answers, then `UNNEST`
    the array to get one row per item.
-   Access result fields with dot notation, e.g. `result.topics`.
-   Use triple-quoted strings (`'''...'''`) for multi-line schemas.

## Execution Limitations

-   Final output is capped at 10000 tokens per group. Longer outputs will be
    truncated.
-   With `output_schema`, the same 10000-token cap applies to the serialized
    JSON of the `STRUCT` result, but oversized results fail instead of being
    truncated. Keep schemas compact and bound list sizes in the instruction
    (e.g. "top 5 topics") to stay under the limit.
-   Arrays of object refs using OBJ.GET_ACCESS_URL() may cause rows to be
    skipped.

## Examples

### User sentiment analysis

```sql
SELECT
  title,
  movie_id,
  AI.AGG(
    review,
    'You will be given user-provided reviews of a movie. Summarize the overall sentiment towards the movie.'
  ) AS sentiment
FROM `bigquery-public-data.imdb.reviews`
WHERE movie_id IN ('tt0339384', 'tt0084787', 'tt0029850')
GROUP BY movie_id, title;
```

### Common categories

```sql
SELECT AI.AGG(
  TO_JSON_STRING(t),
  'These are Wikipedia comments. What are the most used languages?'
)
FROM (SELECT * FROM `bigquery-public-data.samples.wikipedia` LIMIT 30000) AS t;
```

### Most frequent items

```sql
SELECT
  AI.AGG(
    TO_JSON_STRING(t),
    'Among these tech news articles, what are the top 3 most referenced companies and what are they famous for?'
  )
FROM `bigquery-public-data.bbc_news.fulltext` AS t
WHERE t.category = "tech";
```

### Image content summarization

```sql
SELECT AI.AGG(
  STRUCT(OBJ.GET_ACCESS_URL(ref, 'r')),
  'You will be provided with a series of images. What are the most common categories these images belong to?'
)
FROM multimodal.images;
```

### Structured output with `output_schema`

```sql
SELECT
  t.by,
  AI.AGG(
    t.text,
    'These are the hacker news blog posts of a single user. Tell me what topics the user talks about the most. Keep it concise.',
    output_schema => 'topics ARRAY<STRUCT<name STRING NOT NULL, explanation STRING NOT NULL>>'
  ) AS common_topic
FROM `bigquery-public-data.hacker_news.full` AS t
WHERE t.text IS NOT NULL AND t.type = 'story'
GROUP BY t.by
LIMIT 10;
```

### Flatten structured output into rows

```sql
WITH topics AS (
  SELECT
    movie_id,
    AI.AGG(
      review,
      'Summarize the top 3 themes in these reviews of a movie.',
      output_schema => '''
        themes ARRAY<STRUCT<
          theme STRING NOT NULL,
          sentiment STRING NOT NULL OPTIONS(description = 'One of POSITIVE, NEGATIVE, MIXED')
        >> NOT NULL
      '''
    ) AS result
  FROM `bigquery-public-data.imdb.reviews`
  WHERE movie_id IN ('tt0339384', 'tt0084787')
  GROUP BY movie_id
)
SELECT movie_id, t.theme, t.sentiment
FROM topics, UNNEST(result.themes) AS t;
```

[obj-get-access-url]: https://cloud.google.com/bigquery/docs/reference/standard-sql/objectref_functions#objget_access_url
[objectrefruntime]: https://cloud.google.com/bigquery/docs/reference/standard-sql/objectref_functions#objectrefruntime
ai_causal_effect.md 11.2 KB
# BigQuery AI.CAUSAL_EFFECT

`AI.CAUSAL_EFFECT` quantifies the impact of specific interventions on time
series data by comparing observed post-intervention values against an
`ARIMA_PLUS` counterfactual baseline. It returns aggregated effect statistics or
detailed pointwise time series evaluations.

## Syntax Reference

```sql
SELECT
  *
FROM
  AI.CAUSAL_EFFECT(
    { TABLE TABLE_NAME | (QUERY_STATEMENT) },
    data_col => 'DATA_COL',
    timestamp_col => 'TIMESTAMP_COL',
    intervention_timestamp => INTERVENTION_TIMESTAMP
    [, id_cols => ID_COLS]
    [, confidence_level => CONFIDENCE_LEVEL]
    [, output_time_series => OUTPUT_TIME_SERIES]
    [, num_post_intervention_points => NUM_POST_INTERVENTION_POINTS]
  )
```

### Input Arguments

| Argument                           | Requirement  | Type          | Description              |
| :--------------------------------- | :----------- | :------------ | :----------------------- |
| **`input_data`**                   | **Required** | Table / Query | The source table or      |
:                                    :              :               : GoogleSQL query          :
:                                    :              :               : containing time series   :
:                                    :              :               : data from before and     :
:                                    :              :               : after the intervention.  :
| **`data_col`**                     | **Required** | String        | The name of the column   |
:                                    :              :               : with time series values  :
:                                    :              :               : to analyze. The target   :
:                                    :              :               : column must be of type   :
:                                    :              :               : `INT64`, `NUMERIC`,      :
:                                    :              :               : `BIGNUMERIC`, or         :
:                                    :              :               : `FLOAT64`.               :
| **`timestamp_col`**                | **Required** | String        | The name of the column   |
:                                    :              :               : that contains the        :
:                                    :              :               : timestamps for the time  :
:                                    :              :               : series. The target       :
:                                    :              :               : column must be of type   :
:                                    :              :               : `TIMESTAMP`, `DATE`, or  :
:                                    :              :               : `DATETIME`.              :
| **`intervention_timestamp`**       | **Required** | Timestamp /   | A timestamp value that   |
:                                    :              : Date          : indicates when the       :
:                                    :              :               : intervention occurred,   :
:                                    :              :               : dividing the data into   :
:                                    :              :               : pre-intervention and     :
:                                    :              :               : post-intervention        :
:                                    :              :               : periods.                 :
| **`id_cols`**                      | Optional     | Array<String> | The names of columns     |
:                                    :              :               : that identify individual :
:                                    :              :               : time series for parallel :
:                                    :              :               : processing. The target   :
:                                    :              :               : columns must be of type  :
:                                    :              :               : `STRING` or `INT64`.     :
| **`confidence_level`**             | Optional     | Float64       | A `FLOAT64` value in the |
:                                    :              :               : range `[0, 1)`           :
:                                    :              :               : specifying the           :
:                                    :              :               : percentage of future     :
:                                    :              :               : values expected to fall  :
:                                    :              :               : within the prediction    :
:                                    :              :               : interval (default\:      :
:                                    :              :               : `0.95`).                 :
| **`output_time_series`**           | Optional     | Bool          | Determines the level of  |
:                                    :              :               : detail in the output.    :
:                                    :              :               : `FALSE` (default)        :
:                                    :              :               : returns a summary view;  :
:                                    :              :               : `TRUE` returns the       :
:                                    :              :               : detailed time series     :
:                                    :              :               : view including all       :
:                                    :              :               : pointwise data.          :
| **`num_post_intervention_points`** | Optional     | Int64         | Specifies the number of  |
:                                    :              :               : time series points after :
:                                    :              :               : the                      :
:                                    :              :               : `intervention_timestamp` :
:                                    :              :               : to include in the causal :
:                                    :              :               : effect analysis. If you  :
:                                    :              :               : don't specify a value,   :
:                                    :              :               : the analysis includes    :
:                                    :              :               : all data points from the :
:                                    :              :               : `intervention_timestamp` :
:                                    :              :               : to the end of the time   :
:                                    :              :               : series.                  :

### Output Schema

The output includes all columns specified in the `id_cols` argument in addition
to the following columns:

#### Summary View (`output_time_series => FALSE`, default)

| Column Name              | Type      | Description                          |
| :----------------------- | :-------- | :----------------------------------- |
| **`p_value`**            | `FLOAT64` | Two-tailed p-value for the null      |
:                          :           : hypothesis across the entire         :
:                          :           : post-intervention period.            :
| **`prob_causal_effect`** | `FLOAT64` | Probability of a causal effect,      |
:                          :           : calculated as `(1 - p_value)`.       :
| **`absolute_effect`**    | `FLOAT64` | Total cumulative difference between  |
:                          :           : observed and predicted values        :
:                          :           : post-intervention\:                  :
:                          :           : `SUM(actual_value -                  :
:                          :           : expected_value)`.                    :
| **`relative_effect`**    | `FLOAT64` | Relative change of observed values:  |
:                          :           : `SUM(actual_value -                  :
:                          :           : expected_value)/SUM(expected_value)` :
:                          :           : across the post-intervention period. :
| **`status`**             | `STRING`  | Forecast status; empty string on     |
:                          :           : success, or an error string.         :

#### Detailed Pointwise View (`output_time_series => TRUE`)

Includes the summary statistics columns above, repeated across every row, along
with:

| Column Name                | Type        | Description               |
| :------------------------- | :---------- | :------------------------ |
| **`<timestamp_col name>`** | `TIMESTAMP` | Timestamp of the data     |
:                            :             : point from the            :
:                            :             : `timestamp_col` input     :
:                            :             : (both pre- and            :
:                            :             : post-intervention).       :
| **`is_post_intervention`** | `BOOL`      | `TRUE` for timestamps     |
:                            :             : greater than or equal to  :
:                            :             : `intervention_timestamp`, :
:                            :             : `FALSE` for timestamps    :
:                            :             : prior to the              :
:                            :             : intervention.             :
| **`<data_col name>`**      | `FLOAT64`   | Observed value from       |
:                            :             : `data_col` at the         :
:                            :             : specified timestamp.      :
| **`predicted_<data_col     | `FLOAT64`   | Forecasted                |
: name>`**                   :             : (counterfactual) value at :
:                            :             : the specified timestamp   :
:                            :             : (`NULL` for               :
:                            :             : pre-intervention          :
:                            :             : timestamps).              :
| **`lower_bound`**          | `FLOAT64`   | Lower bound of the        |
:                            :             : prediction result (`NULL` :
:                            :             : for pre-intervention      :
:                            :             : timestamps).              :
| **`upper_bound`**          | `FLOAT64`   | Upper bound of the        |
:                            :             : prediction result (`NULL` :
:                            :             : for pre-intervention      :
:                            :             : timestamps).              :

## Limitations

-   A minimum of 3 historical data points in the pre-intervention period is
    required to generate a forecast.

## Examples

### Impact of the COVID-19 Pandemic on NYC Taxi Trips (Detailed Pointwise View)

```sql
SELECT * FROM AI.CAUSAL_EFFECT(
  (
    SELECT
      DATE(pickup_datetime) AS pickup_date,
      COUNT(*) AS trip_count
    FROM `bigquery-public-data.new_york_taxi_trips.tlc_yellow_trips_2020`
    WHERE EXTRACT(YEAR FROM pickup_datetime) = 2020
    GROUP BY pickup_date
  ),
  data_col => 'trip_count',
  timestamp_col => 'pickup_date',
  intervention_timestamp => '2020-03-11', -- WHO declares COVID-19 a pandemic
  num_post_intervention_points => 120,
  output_time_series => TRUE
);
```
ai_classify.md 3.7 KB
# BigQuery AI.Classify

`AI.CLASSIFY` categorizes unstructured data into a predefined set of labels.

## Syntax Reference

```sql
AI.CLASSIFY(
  [ input => ] 'INPUT',
  [ categories => ] 'CATEGORIES'
  [, connection_id => 'CONNECTION_ID' ]
  [, endpoint => 'ENDPOINT' ]
  [, output_mode => 'OUTPUT_MODE' ]
)
```

### Input Arguments

| Argument            | Requirement  | Type          | Description           |
| :------------------ | :----------- | :------------ | :-------------------- |
| **`input`**         | **Required** | String        | The text content to   |
:                     :              :               : classify.             :
| **`categories`**    | **Required** | Array<String> | A list of target      |
:                     :              :               : categories/labels.    :
:                     :              :               : Can be                :
:                     :              :               : `ARRAY<STRING>` or    :
:                     :              :               : `ARRAY<STRUCT<STRING, :
:                     :              :               : STRING>>` (label,     :
:                     :              :               : description).         :
| **`connection_id`** | Optional     | String        | The connection ID to  |
:                     :              :               : use for the LLM.      :
| **`endpoint`**      | Optional     | String        | The model name, e.g., |
:                     :              :               : `'gemini-2.5-flash'`. :
| **`output_mode`**   | Optional     | String        | `'single'` (default)  |
:                     :              :               : or `'multi'`.         :
:                     :              :               : Determines the output :
:                     :              :               : type.                 :

### Output Schema

The output type depends on the `output_mode` argument:

| Output Mode      | output_mode Value | Type            | Description         |
| :--------------- | :---------------- | :-------------- | :------------------ |
| **Single Label** | `NULL` (Default)  | `STRING`        | The single category |
:                  :                   :                 : that best fits the  :
:                  :                   :                 : input.              :
| **Single Label   | `'single'`        | `ARRAY<STRING>` | An array containing |
: (Explicit)**     :                   :                 : exactly one         :
:                  :                   :                 : category string.    :
| **Multi Label**  | `'multi'`         | `ARRAY<STRING>` | An array containing |
:                  :                   :                 : zero or more        :
:                  :                   :                 : matching            :
:                  :                   :                 : categories.         :

## Examples

### Classify text into categories

```sql
SELECT
  content,
  AI.CLASSIFY(
    content,
    categories => ['Spam', 'Not Spam', 'Urgent'],
    connection_id => 'my-project.us.my-connection'
  ) as classification
FROM `dataset.emails`;
```

### Classify text into multiple topics

```
SELECT
  title,
  body,
  AI.CLASSIFY(
    body,
    categories => ['tech', 'sport', 'business', 'politics', 'entertainment', 'other'],
    output_mode => 'multi') AS categories
FROM
  `bigquery-public-data.bbc_news.fulltext`
LIMIT 100;
```

### Classify reviews by sentiment

SELECT AI.CLASSIFY( ('Classify the review by sentiment: ', review), categories
=> [('green', 'The review is positive.'), ('yellow', 'The review is neutral.'),
('red', 'The review is negative.')]) AS ai_review_rating, reviewer_rating AS
human_provided_rating, review FROM `bigquery-public-data.imdb.reviews` WHERE
title = 'The English Patient'
ai_detect_anomalies.md 5.1 KB
# BigQuery AI.Detect_Anomalies

`AI.DETECT_ANOMALIES` uses the pre-trained **TimesFM** model to identify
deviations in time series data without needing to train a custom model.

## Syntax Reference

This function compares a target dataset against a historical dataset to identify
anomalies.

```sql
SELECT *
FROM AI.DETECT_ANOMALIES(
  { TABLE `project.dataset.history_table` | (SELECT * FROM history_query) },
  { TABLE `project.dataset.target_table` | (SELECT * FROM target_query) },
  data_col => 'DATA_COL',
  timestamp_col => 'TIMESTAMP_COL'
  [, model => 'MODEL']
  [, id_cols => ID_COLS]
  [, anomaly_prob_threshold => ANOMALY_PROB_THRESHOLD]
  [, context_window => CONTEXT_WINDOW]
)

```

### Input Arguments

Argument                     | Requirement  | Type          | Description
:--------------------------- | :----------- | :------------ | :----------
**`historical_data`**        | **Required** | Table/Query   | The source table or subquery containing historical data for training context.
**`target_data`**            | **Required** | Table/Query   | The source table or subquery containing data to analyze for anomalies.
**`data_col`**               | **Required** | String        | The numeric column to analyze.
**`timestamp_col`**          | **Required** | String        | The column containing dates/timestamps.
**`id_cols`**                | Optional     | Array<String> | Grouping columns for multiple series (e.g., `['store_id']`).
**`anomaly_prob_threshold`** | Optional     | Float64       | Threshold for anomaly detection (0 to 1). Defaults to 0.95.
**`model`**                  | Optional     | String        | Model version. Allowed options are `'TimesFM 2.0'`, `'TimesFM 2.5'`, and `'TimesFM 3.0'`, with `'TimesFM 2.5'` preferred.
**`context_window`**         | Optional     | Int64         | The number of historical data points the model uses. The min value is 64 and the max value is 2048 for `'TimesFM 2.0'`, and the min value is 64 and the max value is 15360 for `'TimesFM 2.5'` (selected automatically if omitted). For `'TimesFM 3.0'`, must be a multiple of 32 in `[64, 2048]` and defaults to `2048` when omitted.

### Output Schema

| Column                           | Type       | Description                  |
| :------------------------------- | :--------- | :--------------------------- |
| **`id_cols`**                    | (As Input) | Original identifiers for the |
:                                  :            : series.                      :
| **`time_series_timestamp`**      | TIMESTAMP  | Timestamp for the analyzed   |
:                                  :            : points.                      :
| **`time_series_data`**           | FLOAT64    | The original data value.     |
| **`is_anomaly`**                 | BOOL       | TRUE if the point is         |
:                                  :            : identified as an anomaly.    :
| **`lower_bound`**                | FLOAT64    | Lower bound of the expected  |
:                                  :            : range.                       :
| **`upper_bound`**                | FLOAT64    | Upper bound of the expected  |
:                                  :            : range.                       :
| **`anomaly_probability`**        | FLOAT64    | Probability that the point   |
:                                  :            : is an anomaly.               :
| **`ai_detect_anomalies_status`** | STRING     | Error messages or empty      |
:                                  :            : string on success. A minimum :
:                                  :            : of 3 data points is          :
:                                  :            : required.                    :

## Examples

### Basic Anomaly Detection

Detect anomalies in daily bike trips for a specific 2-month window based on
prior history.

```sql
WITH bike_trips AS (
  SELECT EXTRACT(DATE FROM starttime) AS date, COUNT(*) AS num_trips
  FROM `bigquery-public-data.new_york.citibike_trips`
  GROUP BY date
)
SELECT *
FROM AI.DETECT_ANOMALIES(
  -- Historical context (Training data equivalent)
  (SELECT * FROM bike_trips WHERE date <= DATE('2016-06-30')),
  -- Target range (Data to inspect for anomalies)
  (SELECT * FROM bike_trips WHERE date BETWEEN '2016-07-01' AND '2016-09-01'),
  data_col => 'num_trips',
  timestamp_col => 'date',
  model => 'TimesFM 2.5'
);

```

### Multivariate Detection (Multiple Series)

Use `id_cols` to detect anomalies separately for different user types (e.g.,
Subscriber vs. Customer) in the same query.

```sql
WITH bike_trips AS (
    SELECT
      EXTRACT(DATE FROM starttime) AS date, usertype, gender,
      COUNT(*) AS num_trips
    FROM `bigquery-public-data.new_york.citibike_trips`
    GROUP BY date, usertype, gender
  )
SELECT *
FROM
  AI.DETECT_ANOMALIES(
    # Historical data from a query
    (SELECT * FROM bike_trips WHERE date <= DATE('2016-06-30')),
    # Target data from a query
    (SELECT * FROM bike_trips WHERE date BETWEEN '2016-07-01' AND '2016-09-01'),
    data_col => 'num_trips',
    timestamp_col => 'date',
    id_cols => ['usertype', 'gender'],
    model => "TimesFM 2.5",
    anomaly_prob_threshold => 0.8);

```
ai_evaluate.md 2.2 KB
# AI.EVALUATE
Evaluates the accuracy of a forecasting model by comparing predicted values
against actual historical data. It computes standard regression metrics like
MAE, MSE, and RMSE.

## Syntax
```sql
SELECT
  *
FROM
  AI.EVALUATE(
    { TABLE `project.dataset.history_table` | (HISTORY_QUERY) },
    { TABLE `project.dataset.actual_table` | (ACTUAL_QUERY) },
    data_col => 'DATA_COL',
    timestamp_col => 'TIMESTAMP_COL'
    [, model => 'MODEL']
    [, id_cols => ID_COLS]
    [, horizon => HORIZON]
  )
```

## Input Arguments
| Argument | Requirement | Type | Description |
| :--- | :--- | :--- | :--- |
| **`history_data`** | **Required** | | The table or query containing historical data used for the forecast. |
| **`actual_data`** | **Required** | | The table or query containing the actual "ground truth" data. |
| **`data_col`** | **Required** | String | The numeric column to evaluate. |
| **`timestamp_col`** | **Required** | String | The column containing dates/timestamps. |
| **`id_cols`** | Optional | Array<String> | Grouping columns for multiple series. |
| **`horizon`** | Optional | Int64 | Number of points to evaluate. Defaults to 1024. |
| **`model`** | Optional | String | Model version (e.g., `'TimesFM 2.0'`). |

## Output Schema
| Column | Type | Description |
| :--- | :--- | :--- |
| **`id_cols`** | (As Input) | Original identifiers for the series (if provided). |
| **`mean_absolute_error`** | FLOAT64 | Average magnitude of errors in the predictions. |
| **`mean_squared_error`** | FLOAT64 | Average of the squares of the errors. |
| **`root_mean_squared_error`**| FLOAT64 | Square root of the mean squared error. |
| **`mean_absolute_percentage_error`** | FLOAT64 | Mean absolute percentage error for the series. |
| **`symmetric_mean_absolute_percentage_error`** | FLOAT64 | Symmetric mean absolute percentage error for the series. |
| **`ai_evaluate_status`** | STRING | Error messages or empty string on success. |

## Example: Evaluating Forecast Quality
```sql
SELECT * FROM AI.EVALUATE(
  (SELECT * FROM `sales` WHERE date < '2024-01-01'),
  (SELECT * FROM `sales` WHERE date >= '2024-01-01'),
  data_col => 'total_sales',
  timestamp_col => 'date',
  id_cols => ['store_id']
);
```
ai_forecast.md 11.1 KB
# BigQuery AI.Forecast

`AI.FORECAST` leverages the pre-trained **TimesFM** foundation model to generate
forecasts without the need to train and manage custom models.

It has two distinct modes, which take different arguments and return different
output schemas:

*   **Univariate** (`TimesFM 2.0`, `2.5`, `3.0`): forecasts a single target
    column, specified with `data_col`. See section 1.
*   **Multivariate** (`TimesFM 3.0` only): forecasts several target columns in
    one call, specified with `target_cols`, and optionally conditions on past
    and future covariate columns. See section 2.

`data_col` and `target_cols` are mutually exclusive. Pick the matching section
below and do not mix arguments or output columns between the two modes.

Choose the mode from the number of target columns, not from the model version.
For a single target column, use univariate `data_col`, including with
`TimesFM 3.0`. Never pass a one-element array to `target_cols`. The one
exception is covariates: `past_covariate_cols` and `future_covariate_cols` are
only available in multivariate mode, so a forecast that uses covariates must use
`target_cols` even when it has a single target column.

## 1. Univariate Forecasting

### 1.1 Syntax

```sql
SELECT
  *
FROM
  AI.FORECAST(
    { TABLE `project.dataset.table` | (QUERY_STATEMENT) },
    data_col => 'DATA_COL',
    timestamp_col => 'TIMESTAMP_COL'
    [, model => 'MODEL']
    [, id_cols => ID_COLS]
    [, horizon => HORIZON]
    [, confidence_level => CONFIDENCE_LEVEL]
    [, output_historical_time_series => OUTPUT_HISTORICAL_TIME_SERIES]
    [, context_window => CONTEXT_WINDOW]
  )
```

### 1.2 Input Arguments

Argument               | Requirement  | Type          | Description
:--------------------- | :----------- | :------------ | :----------
**`input_data`**       | **Required** |               | The source table or subquery containing historical data.
**`data_col`**         | **Required** | String        | The numeric column to predict.
**`timestamp_col`**    | **Required** | String        | The column containing dates/timestamps.
**`id_cols`**          | Optional     | Array<String> | Grouping columns for multiple series (e.g., `['store_id']`).
**`horizon`**          | Optional     | Int64         | Number of future points to predict. Defaults to 10. The valid input range is [1, 10,000] for `'TimesFM 2.0'` and `'TimesFM 2.5'`, and [1, 1024] for `'TimesFM 3.0'`
**`confidence_level`** | Optional     | Float64       | Confidence interval (0 to 1). Defaults to 0.95.
**`model`**            | Optional     | String        | Model version. Allowed options are `'TimesFM 2.0'`, `'TimesFM 2.5'`, and `'TimesFM 3.0'`, with `'TimesFM 2.5'` preferred.
**`context_window`**   | Optional     | Int64         | The number of historical data points the model uses to forecast. The min value is 64 and the max value is 2048 for `'TimesFM 2.0'`. The min value is 64 and the max value is 15360 for `'TimesFM 2.5'`. For `'TimesFM 3.0'` the value must be a multiple of 32 between 64 and 2048. If not set, the model determines this automatically.

### 1.3 Output Schema

The schema adjusts based on the `output_historical_time_series` flag.

Column                                | Type       | Included if output_historical_time_series=FALSE | Included if output_historical_time_series=TRUE | Description
:------------------------------------ | :--------- | :---------------------------------------------- | :--------------------------------------------- | :----------
**`id_cols`**                         | (As Input) | Yes                                             | Yes                                            | Original identifiers for the series.
**`forecast_timestamp`**              | TIMESTAMP  | **Yes**                                         | No                                             | Timestamp for predicted points.
**`forecast_value`**                  | FLOAT64    | **Yes**                                         | No                                             | The 50% quantile (median) prediction.
**`time_series_timestamp`**           | TIMESTAMP  | No                                              | **Yes**                                        | Uniform timestamp column for both history and forecast.
**`time_series_data`**                | FLOAT64    | No                                              | **Yes**                                        | Merged column: actual values for history, median for forecast.
**`time_series_type`**                | STRING     | No                                              | **Yes**                                        | Label: `'history'` or `'forecast'`.
**`prediction_interval_lower_bound`** | FLOAT64    | Yes                                             | Yes                                            | Lower bound (NULL for historical rows).
**`prediction_interval_upper_bound`** | FLOAT64    | Yes                                             | Yes                                            | Upper bound (NULL for historical rows).
**`confidence_level`**                | FLOAT64    | Yes                                             | Yes                                            | The constant confidence level used.
**`ai_forecast_status`**              | STRING     | Yes                                             | Yes                                            | Error messages or empty string on success. A minimum of 3 data points is required.

### 1.4 Examples

Univariate forecast returning history alongside the forecast:

```sql
WITH
  citibike_trips AS (
    SELECT EXTRACT(DATE FROM starttime) AS date, usertype, COUNT(*) AS num_trips
    FROM `bigquery-public-data.new_york.citibike_trips`
    GROUP BY date, usertype
  )
SELECT *
FROM
  AI.FORECAST(
    TABLE citibike_trips,
    data_col => 'num_trips',
    timestamp_col => 'date',
    id_cols => ['usertype'],
    horizon => 30,
    model => 'TimesFM 2.5',
    output_historical_time_series => true);
```

## 2. Multivariate Forecasting (TimesFM 3.0)

Multivariate forecasting predicts several target columns in a single call, and
can condition the forecast on covariate columns. It requires
`model => 'TimesFM 3.0'`.

Use this mode when there are two or more target columns, or when the forecast
conditions on `past_covariate_cols` or `future_covariate_cols`. For a single
target column without covariates, use section 1 instead.

### 2.1 Syntax

```sql
SELECT
  *
FROM
  AI.FORECAST(
    { TABLE `project.dataset.table` | (QUERY_STATEMENT) },
    target_cols => TARGET_COLS,
    timestamp_col => 'TIMESTAMP_COL',
    model => 'TimesFM 3.0'
    [, id_cols => ID_COLS]
    [, horizon => HORIZON]
    [, past_covariate_cols => PAST_COVARIATE_COLS]
    [, future_covariate_cols => FUTURE_COVARIATE_COLS]
    [, confidence_level => CONFIDENCE_LEVEL]
    [, output_historical_time_series => OUTPUT_HISTORICAL_TIME_SERIES]
    [, context_window => CONTEXT_WINDOW]
  )
```

### 2.2 Input Arguments

Argument                            | Requirement  | Type            | Description
----------------------------------- | ------------ | --------------- | -----------
**`input_data`**                    | **Required** | Table/Query     | The source table or subquery containing the data to forecast.
**`target_cols`**                   | **Required** | Array of String | The list of numeric target columns to predict simultaneously, for example `['num_trips', 'avg_duration']`. Must not be combined with `data_col`.
**`timestamp_col`**                 | **Required** | String          | The column containing dates/timestamps. Supported types are `TIMESTAMP`, `DATE`, and `DATETIME`.
**`model`**                         | **Required** | String          | Must be `'TimesFM 3.0'`.
**`id_cols`**                       | Optional     | Array of String | Grouping column names for multiple time series, for example `['store_id']`. The referenced columns in the source table can be `STRING` or `INT64`.
**`past_covariate_cols`**           | Optional     | Array of String | Historical-only covariate columns, for example `['foot_traffic']`. Values are only known over the historical period.
**`future_covariate_cols`**         | Optional     | Array of String | Covariate columns known in advance, for example `['is_holiday']`. Values must be populated across both the historical period and the forecast horizon.
**`horizon`**                       | Optional     | Int64           | Number of future time series points to predict. Defaults to 10. The valid range is `[1, 1024]`.
**`confidence_level`**              | Optional     | Float64         | Percentage of future values falling in the prediction interval. The valid range is `[0, 1)`. Defaults to 0.95.
**`output_historical_time_series`** | Optional     | Bool            | Determines whether input data is returned along with forecasted data. Defaults to `FALSE`.
**`context_window`**                | Optional     | Int64           | Number of historical points the model uses. Any multiple of 32 between 64 and 2048. Defaults to 2048.

### 2.3 Output Schema

The multivariate output returns one `STRUCT` column per entry in `target_cols`,
named after that target column:

Column                   | Type       | Description
------------------------ | ---------- | -----------
**`id_cols`**            | (As Input) | Original identifiers for the series.
**`<timestamp_col>`**    | TIMESTAMP  | Timestamp for the data point. Keeps the original name of the timestamp column from the input table, for example `date`.
**`<target_col>`**       | STRUCT     | One `STRUCT` per target column, with fields `value` (`FLOAT64`, the 50% quantile prediction, or the historical value when historical output is enabled), `prediction_interval_lower_bound` (`FLOAT64`, NULL for historical rows), and `prediction_interval_upper_bound` (`FLOAT64`, NULL for historical rows).
**`time_series_type`**   | STRING     | Included when `output_historical_time_series=TRUE`. Label of either `'history'` or `'forecast'`.
**`confidence_level`**   | FLOAT64    | The constant confidence level used. Defaults to 0.95.
**`ai_forecast_status`** | STRING     | Error messages, or an empty string on success.

Note that multivariate output keeps the original timestamp column name, while
univariate output renames it to `forecast_timestamp` or `time_series_timestamp`.

### 2.4 Examples

Forecasting two target columns at once, unnesting each `STRUCT`:

```sql
WITH
  citibike_trips AS (
    SELECT
      EXTRACT(DATE FROM starttime) AS date,
      usertype,
      COUNT(*) AS num_trips,
      AVG(tripduration) AS avg_duration
    FROM `bigquery-public-data.new_york.citibike_trips`
    GROUP BY date, usertype
  )
SELECT
  date,
  usertype,
  num_trips.value AS num_trips_forecast,
  num_trips.prediction_interval_lower_bound AS trips_lower_bound,
  num_trips.prediction_interval_upper_bound AS trips_upper_bound,
  avg_duration.value AS avg_duration_forecast,
  avg_duration.prediction_interval_lower_bound AS duration_lower_bound,
  avg_duration.prediction_interval_upper_bound AS duration_upper_bound
FROM
  AI.FORECAST(
    TABLE citibike_trips,
    target_cols => ['num_trips', 'avg_duration'],
    timestamp_col => 'date',
    id_cols => ['usertype'],
    horizon => 30,
    model => 'TimesFM 3.0');
```
ai_generate.md 3.4 KB
# BigQuery AI.Generate

`AI.GENERATE` is a general-purpose function for text and content generation.

## Syntax Reference

```sql
AI.GENERATE(
  [ prompt => ] 'PROMPT',
  [, endpoint => 'ENDPOINT']
  [, model_params => 'MODEL_PARAMS']
  [, output_schema => 'OUTPUT_SCHEMA']
  [, connection_id => 'CONNECTION_ID']
  [, request_type => 'REQUEST_TYPE']
)
```

### Input Arguments

Argument            | Requirement  | Type   | Description
:------------------ | :----------- | :----- | :----------
**`prompt`**        | **Required** | String | The prompt text or instruction for the model.
**`connection_id`** | Optional     | String | The connection ID. Optional if configured via other means or testing.
**`endpoint`**      | Optional     | String | The model name, e.g., `'gemini-3.5-flash-lite'`.
**`output_schema`** | Optional     | String | Schema definition for structured output, e.g., `'answer BOOL, reason STRING'`. Supported data types include `STRING`, `INT64`, `FLOAT64`, `BOOL`, `ARRAY`, and `STRUCT`.
**`request_type`**  | Optional     | String | `'DEDICATED'` or `'SHARED'`.
**`model_params`**  | Optional     | JSON   | JSON object for model parameters (e.g., `temperature`, `max_output_tokens`).

### Supported Endpoints

BigQuery supports the following models:

*   `gemini-3.1-flash-lite`
*   `gemini-3.5-flash`
*   `gemini-3.5-flash-lite`
*   `gemini-3.6-flash`
*   `gemini-3.7-flash`
*   `gemini-3.8-flash`
*   `gemini-4-argon`

### Output Schema

Returns a `STRUCT` with the following fields:

| Column Name         | Type                 | Description                    |
| :------------------ | :------------------- | :----------------------------- |
| **`result`**        | `STRING` (or Custom) | The generated content. If      |
:                     :                      : `output_schema` is used, this  :
:                     :                      : field is replaced by the       :
:                     :                      : schema's fields.               :
| **`status`**        | `STRING`             | API response status (empty on  |
:                     :                      : success).                      :
| **`full_response`** | `JSON`               | The complete raw JSON response |
:                     :                      : from the model (including      :
:                     :                      : safety ratings, usage          :
:                     :                      : metadata).                     :

## Examples

### Basic Text Generation

```sql
SELECT
  AI.GENERATE(
    'Summarize this article: ' || article_content
  ) as summary
FROM `dataset.articles`
LIMIT 5;
```

### Structured Output Generation

```sql
SELECT
  AI.GENERATE(
    'Extract the date and amount from this invoice: ' || invoice_text,
    output_schema => 'date STRING, amount FLOAT64'
  ) as extracted_data
FROM `dataset.invoices`;
```

### Process images in a Cloud Storage bucket

```sql
CREATE SCHEMA IF NOT EXISTS bqml_tutorial;

CREATE OR REPLACE EXTERNAL TABLE bqml_tutorial.product_images
  WITH CONNECTION DEFAULT OPTIONS (
    object_metadata = 'SIMPLE',
    uris = ['gs://cloud-samples-data/bigquery/tutorials/cymbal-pets/images/*.png']);

SELECT
  uri,
  STRING(OBJ.GET_ACCESS_URL(ref,'r').access_urls.read_url) AS signed_url,
  AI.GENERATE(
    ("What is this: ", OBJ.GET_ACCESS_URL(ref, 'r')),
    output_schema =>
      "image_description STRING, entities_in_the_image ARRAY<STRING>").*
FROM bqml_tutorial.product_images
WHERE uri LIKE "%aquarium%";
```
ai_generate_embedding.md 2.0 KB
# AI.GENERATE_EMBEDDING
Used to generate high-dimensional numerical vectors (embeddings) for text or
visual content. These embeddings can be used for semantic search, clustering,
and recommendation systems.

## Syntax

```sql
SELECT
  *
FROM
  AI.GENERATE_EMBEDDING(
    MODEL `project.dataset.model`,
    { TABLE `project.dataset.table` | (QUERY_STATEMENT) }
    [, STRUCT(
      [TASK_TYPE AS task_type]
      [, OUTPUT_DIMENSIONALITY AS output_dimensionality]) ]
  )
```

## Input Arguments

Argument                    | Requirement   | Type   | Description
:-------------------------- | :------------ | :----- | :----------
**`model`**                 | **Required**  |        | The model resource (e.g., `project.dataset.model`).
**`input_data`**            | **Required*** |        | The source table or `SELECT` statement containing the data to embed. The text in the column named `content` is sent to the model. If your table doesn't have a `content` column, use a `SELECT` statement to alias an existing table column. An error occurs if no `content` column exists.
**`task_type`**             | Optional      | String | The intended downstream application (e.g., `RETRIEVAL_QUERY`, `RETRIEVAL_DOCUMENT`).
**`output_dimensionality`** | Optional      | Int64  | The number of dimensions to use when generating embeddings.

\* *`input_data` is optional for matrix factorization models.*

## Output Schema
| Column | Type | Description |
| :--- | :--- | :--- |
| **`[Input Columns]`** | (As Input) | Every column included in your input data. |
| **`embedding`** | ARRAY<FLOAT64> | The generated numerical vector. |
| **`statistics`** | JSON | Metadata about the generation, such as token count. |
| **`status`** | STRING | Execution status; contains error messages on failure. |

## Example: Generating Text Embeddings

```sql
-- Generate embeddings for a literal string
SELECT *
FROM
  AI.GENERATE_EMBEDDING(
    MODEL `mydataset.text_embedding`,
    (SELECT "Example text to embed" AS content)
);
```
ai_generate_table.md 3.3 KB
# AI.GENERATE_TABLE
Uses Gemini models to extract information into a predefined SQL schema. It is a
"Table-Valued Function," meaning it is called in the `FROM` clause.

## Syntax

```sql
SELECT
  *
FROM
  AI.GENERATE_TABLE(
    MODEL `project.dataset.model`,
    { TABLE `project.dataset.table` | (QUERY_STATEMENT) },
  STRUCT(
    OUTPUT_SCHEMA AS output_schema
    [, MAX_OUTPUT_TOKENS AS max_output_tokens]
    [, TOP_P AS top_p]
    [, TEMPERATURE AS temperature]
    [, STOP_SEQUENCES AS stop_sequences]
    [, SAFETY_SETTINGS AS safety_settings]
    [, REQUEST_TYPE AS request_type])
  )
```

## Input Arguments

Argument                | Requirement  | Type          | Description
:---------------------- | :----------- | :------------ | :----------
**`model`**             | **Required** |               | The remote model resource (e.g., `project.dataset.model`).
**`input_data`**        | **Required** |               | The source table or `SELECT` statement. Must contain a column named or aliased as `prompt`.
**`output_schema`**     | **Required** | String        | A `STRUCT` containing SQL-style column definitions (e.g., `"name STRING, qty INT64"`). Supported data types include `STRING`, `INT64`, `FLOAT64`, `BOOL`, `ARRAY`, and `STRUCT` (do not use `DATE` or `TIMESTAMP`; extract as `STRING` and cast in SQL).
**`max_output_tokens`** | Optional     | Int64         | [1, 8192]. Limits response length.
**`temperature`**       | Optional     | Float64       | [0.0, 2.0]. Degree of randomness (0.0 is recommended for deterministic responses).
**`top_p`**             | Optional     | Float64       | [0.0, 1.0]. Changes how the model selects tokens for output.
**`stop_sequences`**    | Optional     | Array<String> | Strings that halt model generation if matched.
**`safety_settings`**   | Optional     | Array<Struct> | Thresholds to filter hate speech, harassment, etc.
**`request_type`**      | Optional     | String        | `SHARED`, `DEDICATED`, or `UNSPECIFIED` (defaults to `UNSPECIFIED`).

### Prompt Construction (STRUCT Fields)
When using a `QUERY_STATEMENT`, you can build multimodal prompts by combining
types:

* **`STRING` / `ARRAY<STRING>`**: Literal text or column names.
* **`ObjectRefRuntime`**: Use `OBJ.GET_ACCESS_URL(col, 'r')` for images/PDFs.

## Output Schema

The output table is a join of your source data and the model's generated
content. It preserves all original input columns to maintain traceability.

| Column | Type | Description |
| :--- | :--- | :--- |
| **`[Input Columns]`** | (As Input) | Every column included in your input `TABLE` or `QUERY_STATEMENT`. |
| **`[Schema Columns]`**| (As Defined)| The typed columns you specified in the `OUTPUT_SCHEMA` argument. |
| **`full_response`** | JSON        | The raw, unparsed JSON response from the underlying Gemini model. |
| **`status`** | STRING      | Execution status; will contain error messages if a row fails extraction. |

## Example: Preserving Keys During LLM Summarization

```sql
-- The output includes 'ticket_id' from the input and 'priority' and 'issue_summary' from the AI schema
SELECT
  ticket_id,
  priority,
  issue_summary
FROM AI.GENERATE_TABLE(
  MODEL `prod.models.gemini_flash`,
  (SELECT ticket_id, body AS prompt FROM `support.tickets`),
  STRUCT("priority STRING, issue_summary STRING" AS output_schema)
)
```
ai_if.md 2.0 KB
# BigQuery AI.If

`AI.IF` is a semantic boolean function used to evaluate a condition described in
natural language.

The function can be used to filter and join data based on conditions described
in natural language or multimodal input. The following are common use cases:

-   Sentiment analysis: Find customer reviews with negative sentiment.
-   Topic analysis: Identify news articles related to a specific subject.
-   Image analysis: Select images that contain a specific item.
-   Security: Identify suspicious emails.

## Syntax Reference

```sql
AI.IF(
  [ prompt => ] 'PROMPT'
  [, connection_id => 'CONNECTION_ID' ]
  [, endpoint => 'ENDPOINT' ]
)
```

### Input Arguments

| Argument            | Requirement  | Type          | Description            |
| :------------------ | :----------- | :------------ | :--------------------- |
| **`prompt`**        | **Required** | String/Struct | The prompt text or a   |
:                     :              :               : struct/tuple of        :
:                     :              :               : `(data, instruction)`. :
| **`connection_id`** | Optional     | String        | The connection ID to   |
:                     :              :               : use for the LLM.       :
| **`endpoint`**      | Optional     | String        | The model endpoint     |
:                     :              :               : (e.g.                  :
:                     :              :               : `'gemini-2.5-flash'`). :

### Output Schema

| Column Name         | Type   | Description                               |
| :------------------ | :----- | :---------------------------------------- |
| **(Scalar Result)** | `BOOL` | `TRUE` if the condition is met, `FALSE`   |
:                     :        : otherwise. Returns `NULL` on error/safety :
:                     :        : filter.                                   :

## Examples

### Filter rows based on semantic meaning

```sql
SELECT *
FROM `dataset.table`
WHERE AI.IF(
  (content_column, 'Is this review positive?')
);
```
ai_key_drivers.md 4.6 KB
# BigQuery AI.Key_Drivers

`AI.KEY_DRIVERS` automatically identifies the key dimensional segments most
responsible for driving changes in a specified metric between a defined interest
group and a reference group.

## Syntax Reference

```sql
SELECT
  *
FROM
  AI.KEY_DRIVERS(
    { TABLE TABLE | (QUERY_STATEMENT) },
    metric_col => 'METRIC_COL',
    dimension_cols => DIMENSION_COLS,
    interest_label_col => 'INTEREST_LABEL_COL'
    [, min_apriori_support => MIN_APRIORI_SUPPORT]
    [, top_k => TOP_K]
    [, enable_pruning => ENABLE_PRUNING]
  )
```

### Input Arguments

Argument                  | Requirement  | Type            | Description
:------------------------ | :----------- | :-------------- | :----------
**`input_data`**          | **Required** |                 | The source table or subquery containing the data to analyze.
**`metric_col`**          | **Required** | `STRING`        | Metric column name. Must be of type: INT64, NUMERIC, BIGNUMERIC, or FLOAT64. The values in the metric column that you use in the `metric_col` option must be non-negative, unless you specify 0 for the `min_apriori_support` value.
**`interest_label_col`**  | **Required** | `STRING`        | Boolean column name: `TRUE` for interest group, `FALSE` for reference group.
**`dimension_cols`**      | **Required** | `ARRAY<STRING>` | 1-12 dimension columns (INT64, BOOL, STRING); cannot be `metric_col` or `interest_label_col`.
**`min_apriori_support`** | Optional     | `FLOAT64`       | Minimum apriori support threshold [0, 1] for output segments. Default: 0.1. Cannot be used with `top_k`.
**`top_k`**               | Optional     | `INT64`         | Return top k insights [1, 1M] by apriori support. If unset, uses `min_apriori_support=0.1`. Cannot be used with `min_apriori_support`.
**`enable_pruning`**      | Optional     | `BOOL`          | If `TRUE` (default), redundant insights are pruned. If `FALSE`, all insights meeting thresholds are returned. Two segments are redundant if two conditions are met: 1) their metric values are equal 2) The dimensions and corresponding values of one row are a subset of the dimensions and corresponding values of the other. In this case, the row with more dimensions (the more descriptive row) is kept.

### Output Schema

Returns a `STRUCT` with the following fields:

Column Name                          | Type            | Description
:----------------------------------- | :-------------- | :----------
**`drivers`**                        | `ARRAY<STRING>` | Provides a list of drivers, or dimension values of interest, which describes each of the segments.
**`metric_interest`**                | `NUMERIC`       | The sum of the metric_column for the data in the interest segment.
**`metric_reference`**               | `NUMERIC`       | The sum of the metric_column for data in the reference segment.
**`difference`**                     | `NUMERIC`       | The difference between the interest and reference metric values for a segment.
**`relative_difference`**            | `NUMERIC`       | The relative change of a segment, calculated as the difference divided by the reference metric value.
**`unexpected_difference`**          | `NUMERIC`       | Measures deviation of segment from the rest of the population's growth. Calculated as: (segment relative_difference - complement relative_difference) * segment reference metric.
**`relative_unexpected_difference`** | `NUMERIC`       | The unexpected_difference divided by the expected interest metric value for a segment.
**`contribution`**                   | `NUMERIC`       | Contains the absolute value of the difference value: `ABS(difference)`.
**`apriori_support`**                | `NUMERIC`       | Segment size relative to the total population (filters small segments).

## Examples

### Identifying Key Drivers in 2024 H2 Liquor Sales

```sql
WITH InputData AS (
  SELECT
    sale_dollars,
    city,
    category_name,
    vendor_name,
    (date > '2024-07-01') AS IS_H2
  FROM `bigquery-public-data.iowa_liquor_sales.sales`
  WHERE EXTRACT(YEAR FROM DATE) = 2024
)
SELECT *
FROM AI.KEY_DRIVERS(
  TABLE InputData,
  metric_col => 'sale_dollars',
  dimension_cols => ['city', 'vendor_name', 'category_name'],
  interest_label_col => 'IS_H2',
  min_apriori_support => 0
);
```

### Finding Top 5 Key Drivers in Bottle Costs

```sql
SELECT *
FROM AI.KEY_DRIVERS(
  (
    SELECT
      state_bottle_cost,
      city,
      category_name,
      (EXTRACT(MONTH FROM date) >= 7) AS is_h2
    FROM `bigquery-public-data.iowa_liquor_sales.sales`
    WHERE EXTRACT(YEAR FROM date) = 2024
  ),
  metric_col => 'state_bottle_cost',
  dimension_cols => ['city', 'category_name'],
  interest_label_col => 'is_h2',
  top_k => 5
);
```
ai_predict.md 8.5 KB
# BigQuery AI.Predict

`AI.PREDICT` leverages the pre-trained **TabFM** foundation model to perform
prediction (classification or regression) tasks on tabular data without the need
to train and manage custom models. Under the hood, this function applies an
In-Context Learning (ICL) approach: it embeds the training data to construct a
temporary model representation (kv cache) and uses it to predict labels for the
prediction data within the lifetime of a single query execution.

## Syntax Reference

```sql
SELECT
  *
FROM
  AI.PREDICT(
    { TABLE `project.dataset.training_table` | (TRAINING_QUERY) },
    { TABLE `project.dataset.prediction_table` | (PREDICTION_QUERY) }
    [, label_col => 'LABEL_COL']
    [, model => 'MODEL']
  )
```

### Input Arguments

| Argument               | Requirement  | Type     | Description        |
| :--------------------- | :----------- | :------- | :----------------- |
| **`training_table`**   | **Required** | Relation | The source table   |
:                        :              :          : or subquery        :
:                        :              :          : containing         :
:                        :              :          : training data.     :
:                        :              :          : This data MUST     :
:                        :              :          : contain the label  :
:                        :              :          : column. Only       :
:                        :              :          : Numerical (e.g.,   :
:                        :              :          : INT64, FLOAT64),   :
:                        :              :          : STRING, and BOOL   :
:                        :              :          : columns are        :
:                        :              :          : supported.         :
| **`prediction_table`** | **Required** | Relation | The source table   |
:                        :              :          : or subquery        :
:                        :              :          : containing         :
:                        :              :          : prediction data.   :
:                        :              :          : Every column in    :
:                        :              :          : the                :
:                        :              :          : `training_table`   :
:                        :              :          : (except the        :
:                        :              :          : `label_col`) MUST  :
:                        :              :          : exist in the       :
:                        :              :          : `prediction_table` :
:                        :              :          : with the exact     :
:                        :              :          : same               :
:                        :              :          : case-insensitive   :
:                        :              :          : name and matching  :
:                        :              :          : types. Only        :
:                        :              :          : Numerical (e.g.,   :
:                        :              :          : INT64, FLOAT64),   :
:                        :              :          : STRING, and BOOL   :
:                        :              :          : columns are        :
:                        :              :          : supported.         :
| **`label_col`**        | Optional     | String   | The name of the    |
:                        :              :          : label column in    :
:                        :              :          : the training data. :
:                        :              :          : Defaults to        :
:                        :              :          : `'label'`.         :
| **`model`**            | Optional     | String   | The model version. |
:                        :              :          : If specified, the  :
:                        :              :          : value MUST be the  :
:                        :              :          : literal `'TabFM    :
:                        :              :          : 1.0'`. Defaults to :
:                        :              :          : `'TabFM 1.0'`.     :

### Constraints & Limitations

> [!WARNING] **Same Table Split (Avoid Label Leakage)**: If you use the EXACT
> same table (or query) for both the `training_table` and `prediction_table`
> arguments, you MUST split the data into non-overlapping sets to avoid label
> leakage. You can use a helper column with `RAND() <= 0.8` to split the data
> (e.g., 80% for training, 20% for prediction).
>
> Example:
>
> ```sql
> WITH prepared_data AS (
>   SELECT *, RAND() <= 0.8 AS training
>   FROM `bigquery-public-data.ml_datasets.penguins`
>   WHERE body_mass_g > 0
> )
> SELECT
>   *
> FROM
>   AI.PREDICT(
>     # Training data
>     (SELECT * EXCEPT(training) FROM prepared_data WHERE training),
>     # Prediction data
>     (SELECT * EXCEPT(training) FROM prepared_data WHERE NOT training),
>     label_col => 'body_mass_g'
>   );
> ```

-   **Feature Column Limit**: The training and prediction data can include up to
    50 feature columns.
-   **Classification Category Limit**: For classification tasks, you can
    classify data into at most 10 different categories.
-   **Task Type Detection**:
    -   **CLASSIFICATION**: Automatically triggered if the label column is of
        type STRING or BOOL.
    -   **REGRESSION**: Automatically triggered if the label column is of a
        Numerical type.

### Output Schema

The output schema includes:

Column                                  | Type                                                    | Description
:-------------------------------------- | :------------------------------------------------------ | :----------
**`predicted_<label_col>`**             | STRING or BOOL (Classification) or Numeric (Regression) | The predicted label. The data type is the same as the label column in the training data.
**`predicted_<label_col>_probs`**       | ARRAY<STRUCT<label STRING, prob FLOAT64>>               | (Classification only) An array of structs containing `label` (STRING) and `prob` (FLOAT64) representing the probability of each class.
**All columns from `prediction_table`** | (As Input)                                              | All columns from the input `prediction_table` relation.

## Examples

### Classification Example (Inline Data)

```sql
SELECT *
FROM
  AI.PREDICT(
    (
      SELECT
        'Alice' AS customer,
        150.0 AS spend,
        2 AS calls,
        24 AS tenure,
        TRUE AS churned
      UNION ALL
      SELECT
        'Bob' AS customer,
        850.0 AS spend,
        1 AS calls,
        48 AS tenure,
        FALSE AS churned
    ),
    (
      SELECT
        'Bob' AS customer,
        850.0 AS spend,
        1 AS calls,
        48 AS tenure
      UNION ALL
      SELECT
        'Charlie' AS customer,
        200.0 AS spend,
        4 AS calls,
        12 AS tenure
    ),
    label_col => 'churned'
  );
```

### Classification Example (Tables)

```sql
SELECT *
FROM
  AI.PREDICT(
    TABLE `my_project.my_dataset.customer_train`,
    TABLE `my_project.my_dataset.customer_test`,
    label_col => 'churned'
  );
```

### Regression Example (Tables)

```sql
SELECT *
FROM
  AI.PREDICT(
    TABLE `my_project.my_dataset.housing_train`,
    TABLE `my_project.my_dataset.housing_test`,
    label_col => 'price'
  );
```

### Same Table Split Example (Regression)

If you must use the same table for both training and prediction, you MUST split
the data to avoid label leakage. This example predicts the numeric `body_mass_g`
column (Regression).

```sql
WITH prepared_data AS (
  SELECT *, RAND() <= 0.8 AS training
  FROM `bigquery-public-data.ml_datasets.penguins`
  WHERE body_mass_g > 0
)
SELECT
  *
FROM
  AI.PREDICT(
    # Training data
    (SELECT * EXCEPT(training) FROM prepared_data WHERE training),
    # Prediction data
    (SELECT * EXCEPT(training) FROM prepared_data WHERE NOT training),
    label_col => 'body_mass_g'
  );
```

### Same Table Split Example (Classification)

If you must use the same table for both training and prediction, you MUST split
the data to avoid label leakage. This example predicts the string `species`
column (Classification).

```sql
WITH prepared_data AS (
  SELECT *, RAND() <= 0.8 AS training
  FROM `bigquery-public-data.ml_datasets.penguins`
  WHERE species IS NOT NULL
)
SELECT
  *
FROM
  AI.PREDICT(
    # Training data
    (SELECT * EXCEPT(training) FROM prepared_data WHERE training),
    # Prediction data
    (SELECT * EXCEPT(species, training) FROM prepared_data WHERE NOT training),
    label_col => 'species'
  );
```
ai_score.md 1.9 KB
# BigQuery AI.Score

The `AI.SCORE` function is commonly used with the ORDER BY clause and works well
when you want to rank items. The following are common use cases:

-   Retail: Find the top 5 most negative customer reviews about a product.
-   Hiring: Find the top 10 resumes that appear most qualified for a job post.
-   Customer success: Find the top 20 best customer support interactions.

## Syntax Reference

```sql
AI.SCORE(
  [ prompt => ] 'PROMPT'
  [, connection_id => 'CONNECTION_ID' ]
  [, endpoint => 'ENDPOINT' ]
)
```

### Input Arguments

| Argument            | Requirement  | Type          | Description            |
| :------------------ | :----------- | :------------ | :--------------------- |
| **`prompt`**        | **Required** | String/Struct | The prompt text or a   |
:                     :              :               : struct/tuple of        :
:                     :              :               : `(data, instruction)`. :
| **`connection_id`** | Optional     | String        | The connection ID to   |
:                     :              :               : use for the LLM.       :
| **`endpoint`**      | Optional     | String        | The model endpoint     |
:                     :              :               : (e.g.                  :
:                     :              :               : `'gemini-2.5-flash'`). :

### Output Schema

| Column Name         | Type      | Description                                |
| :------------------ | :-------- | :----------------------------------------- |
| **(Scalar Result)** | `FLOAT64` | A numerical score representing the degree  |
:                     :           : to which the data matches the instruction. :

## Examples

### Rank rows by semantic relevance

```sql
SELECT *
FROM `dataset.table`
ORDER BY AI.SCORE(
  (content_column, 'relevance to sports'),
  connection_id => 'my-project.us.my-connection'
) DESC
LIMIT 10;
```
ai_search.md 3.7 KB
# BigQuery AI.Search

`AI.SEARCH` is a table-valued function for semantic search on tables that have
autonomous embedding generation enabled. If your table has a column that has
generated_expression metadata with format "AI.EMBED(source_column)", then
AI.SEARCH uses it to optimize the search.

You can use AI.SEARCH to help with the following tasks:

-   Semantic search: search entities ranked by semantic similarity.
-   Recommendation: return entities with attributes similar to a given entity.
-   Classification: return the class of entities whose attributes are similar to
    the given entity.
-   Clustering: cluster entities whose attributes are similar to a given entity.
-   Outlier detection: return entities whose attributes are least related to the
    given entity.

## Syntax Reference

```sql
AI.SEARCH(
  { TABLE base_table | base_table_query },
  column_to_search,
  query_value
  [, top_k => top_k_value ]
  [, distance_type => distance_type_value ]
  [, options => options_value]
)
```

**IMPORTANT:** Do not add "column_to_search =>" prefixes to the column_to_search
argument because column_to_search is a positional argument.

### Input Arguments

Argument               | Requirement  | Type     | Description
:--------------------- | :----------- | :------- | :----------
**`base_table`**       | **One Of**   | Table    | The table to search for nearest neighbor embeddings. The table must have autonomous embedding generation enabled.
**`base_table_query`** | **One Of**   | Subquery | The query that you can use to pre-filter the base table. Only SELECT, FROM, and WHERE clauses are allowed in this query. Don't apply any filters to the embedding column.
**`column_to_search`** | **Required** | STRING   | A STRING literal that contains the name of the string column to search
**`query_value`**      | **Required** | STRING   | A string literal that represents the search query.
**`top_k`**            | Optional     | INT64    | A named argument with an INT64 value, specifies the number of nearest neighbors to return. The default is 10.
**`distance_type`**    | Optional     | STRING   | A named argument with a STRING value. distance_type_value specifies the type of metric to use to compute the distance between two vectors. Supported distance types are EUCLIDEAN, COSINE, and DOT_PRODUCT. The default is EUCLIDEAN. Recommend to use COSINE.
**`options`**          | Optional     | STRING   | A named argument with a JSON-formatted STRING value that specifies the following search options: `fraction_lists_to_search` or `use_brute_force`

### Output Schema

Column Name    | Type    | Description
:------------- | :------ | :----------------------------------------------------
**`base`**     | STRUCT  | A struct containing all columns from the input table.
**`distance`** | FLOAT64 | The distance score between the query and the result.

## Examples

```sql
# Create a table with a product column, a description column, and an autonomous
# embedding generation column over the description column.
CREATE TABLE mydataset.products (
  name STRING,
  description STRING,
  description_embedding STRUCT<result ARRAY<FLOAT64>, status STRING>
    GENERATED ALWAYS AS (AI.EMBED(
      description,
      connection_id => 'us.example_connection',
      endpoint => 'text-embedding-005'
    ))
    STORED OPTIONS( asynchronous = TRUE )
);

# Get all really fun toy products.
SELECT
  base.name,
  base.description,
  distance
FROM AI.SEARCH(TABLE mydataset.products, 'description', "A really fun toy", distance_type => "COSINE");

# Get top 5 fun toy products.
SELECT DISTINCT(base.description)
FROM AI.SEARCH(TABLE `mydataset.products`, 'description', "A really fun toy", distance_type => "COSINE", top_k => 100)
LIMIT 5;
```
ai_similarity.md 2.7 KB
# BigQuery AI.Similarity

`AI.SIMILARITY` computes the semantic similarity between two inputs.

Use cases include the following:

-   Semantic search: Search for text or images based off a description, without
    having to match specific keywords.
-   Recommendation: Return entities with attributes similar to a given entity.

## Syntax Reference

```sql
AI.SIMILARITY(
  content1 => 'CONTENT1',
  content2 => 'CONTENT2'
  [, endpoint => 'ENDPOINT']
  [, model_params => 'MODEL_PARAMS']
  [, connection_id => 'CONNECTION_ID']
)
```

### Input Arguments

| Argument            | Requirement  | Type      | Description              |
| :------------------ | :----------- | :-------- | :----------------------- |
| **`content1`**      | **Required** | String or | The first text content   |
:                     :              : ObjectRef : or image context.        :
| **`content2`**      | **Required** | String or | The second text content  |
:                     :              : ObjectRef : or image to compare      :
:                     :              :           : against.                 :
| **`connection_id`** | Optional     | String    | The connection ID to use |
:                     :              :           : for the LLM.             :
| **`endpoint`**      | Optional     | String    | The model endpoint (e.g. |
:                     :              :           : `'text-embedding-005'`). :
| **`model_params`**  | Optional     | JSON      | JSON object for model    |
:                     :              :           : parameters (e.g.,        :
:                     :              :           : `temperature`,           :
:                     :              :           : `max_output_tokens`).    :

### Output Schema

| Column Name         | Type      | Description                         |
| :------------------ | :-------- | :---------------------------------- |
| **(Scalar Result)** | `FLOAT64` | A similarity score (e.g., cosine    |
:                     :           : similarity). Returns null if error. :

## Examples

### Compute semantic similarity between two text inputs

```sql
SELECT AI.SIMILARITY(
  content1 => 'The cat sat on the mat',
  content2 => 'A feline is resting on the rug'
) as similarity_score;
```

### Compute semantic similarity between text and image

```sql
CREATE SCHEMA IF NOT EXISTS cymbal_pets;

CREATE OR REPLACE EXTERNAL TABLE cymbal_pets.product_images
WITH CONNECTION DEFAULT
OPTIONS (
  object_metadata = 'SIMPLE',
  uris = ['gs://cloud-samples-data/bigquery/tutorials/cymbal-pets/images/*.png']
);

SELECT
  uri,
  OBJ.GET_READ_URL(ref) AS signed_url,
  ai.similarity(
    "aquarium device",
    ref,
    endpoint => 'multimodalembedding@001') AS similarity_score
FROM cymbal_pets.product_images
ORDER BY similarity_score DESC
LIMIT 3;
```
attribution.md 1.8 KB
# Usage Attribution

**MUST READ**: Before executing any `gcloud`, REST API, or MCP command with
this skill, follow these usage attribution instructions. Tag every command you
execute directly in the terminal so usage can be attributed. The tag identifies
only the skill and its version; it carries no user data.

-   **`gcloud` CLI Commands**: Prefix every `gcloud` invocation, whatever the
    subcommand, with the metrics environment variable. Set it inline on each
    command because shell state may not persist between commands:

    ```bash
    CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:bigquery-ai-ml)" \
    gcloud <command> [flags]
    ```

    Do not use `gcloud config set` for this: it would persist beyond the current
    task and mislabel unrelated usage.

-   **Direct HTTP, REST, and MCP Requests**: On direct HTTP calls to Google
    Cloud APIs (for example with `curl`) or HTTP requests to a remote MCP
    server, include `agent-skills/1.0 (skill:bigquery-ai-ml)` in the `User-Agent`
    header. If a `User-Agent` header is already specified, append this string to
    the end of it rather than overwriting existing `User-Agent` data — the
    collection pipeline parses the `agent-skills/<version>` and `skill:<name>`
    tokens, so any rewording breaks attribution:

    ```
    User-Agent: <existing_user_agent> agent-skills/1.0 (skill:bigquery-ai-ml)
    ```

-   **Constraint for Generated Code**: The tracking prefix is strictly for
    commands you execute directly in the terminal. Do NOT include this tracking
    prefix in generated scripts, Terraform templates, or code provided to the
    user for their own repositories.

-   **User Opt-Out**: If the user asks to disable or remove tracking or
    attribution tags, omit the `CLOUDSDK_METRICS_REQUEST_ATTRIBUTION` variable
    and custom `User-Agent` suffix from all commands.
ml_contribution_analysis.md 4.8 KB
# Contribution Analysis

Contribution analysis, also called key driver analysis, is a method used to
generate insights about changes to key metrics in your multi-dimensional data.

## Syntax

To use contribution analysis in BigQuery ML, create a contribution analysis
model with the CREATE MODEL statement.

After you have created a contribution analysis model, you can use the
ML.GET_INSIGHTS function to retrieve the metric information calculated by the
model.

### CREATE MODEL Syntax

```sql
CREATE OR REPLACE MODEL `project.dataset.model_name`
OPTIONS (
  MODEL_TYPE = 'CONTRIBUTION_ANALYSIS',
  CONTRIBUTION_METRIC = 'contribution_metric',
  IS_TEST_COL = 'is_test_col'
  [, DIMENSION_ID_COLS = dimension_column_array]
  [, MIN_APRIORI_SUPPORT = min_apriori_support]
  [, TOP_K_INSIGHTS_BY_APRIORI_SUPPORT = top_k_insights_by_apriori_support]
  [, PRUNING_METHOD = {'NO_PRUNING', 'PRUNE_REDUNDANT_INSIGHTS'}]
)
AS query_statement;
```

### Options
| Option | Requirement | Type | Description |
| :--- | :--- | :--- | :--- |
| **`MODEL_TYPE`** | **Required** | String | Must be `'CONTRIBUTION_ANALYSIS'`. |
| **`CONTRIBUTION_METRIC`** | **Required** | String | The metric to analyze. Supported metric is `SUM(metric_column_name)`. |
| **`IS_TEST_COL`** | **Required** | String | The name of the boolean column that distinguishes test data (TRUE) from control data (FALSE). |
| **`DIMENSION_ID_COLS`** | Optional | Array<String> | The columns to use as dimensions for segmenting the data. Defaults to all columns in the input data that aren't specified in other options. Restricted to columns of type `INT64`, `BOOL`, or `STRING`. Limited to a max of 50 columns.|
| **`MIN_APRIORI_SUPPORT`** | Optional | Float64 | Minimum support threshold to prune small segments. Cannot be used with `TOP_K_INSIGHTS_BY_APRIORI_SUPPORT`. Defaults to 0.1 if neither is specified. The value is in the range of [0, 1]. |
| **`TOP_K_INSIGHTS_BY_APRIORI_SUPPORT`** | Optional | Int64 | The maximum number of insights to output with the highest apriori support value. Cannot be used with `MIN_APRIORI_SUPPORT`. This value should be within the interval [1, 1,000,000]|
| **`PRUNING_METHOD`** | Optional | String | The pruning method used to filter insights. Supported: `'NO_PRUNING'`, `'PRUNE_REDUNDANT_INSIGHTS'`. Defaults to `'NO_PRUNING'`. `PRUNE_REDUNDANT_INSIGHTS` prunes redundant segments, excluding the `all` segment. Two segments are redundant if two conditions are met: 1) their metric values are equal 2) The dimension IDs and corresponding values of one row are a subset of the dimension IDs and corresponding values of the other. In this case, the row with more dimension IDs (the more descriptive row) is kept.|

---

## ML.GET_INSIGHTS Syntax

Use `ML.GET_INSIGHTS` to retrieve the results from the model:

```sql
ML.GET_INSIGHTS(
  MODEL `PROJECT_ID.DATASET.MODEL_NAME`
)
```

### Output Schema
| Column | Description |
| :--- | :--- |
| **`contributors`** | The dimension values for a given segment (e.g., `['dim1=val1', 'dim2=val2']`). |
| **`metric_test`** | A numeric value that contains the sum of the value of the metric column in the test dataset for the given segment. |
| **`metric_control`** | A numeric value that contains the sum of the value of the metric column in the control dataset for the given segment. |
| **`difference`** | A numeric value that contains the difference between the metric_test and metric_control values: `metric_test - metric_control`. |
| **`relative_difference`** | A numeric value that contains the relative change in the segment value between the test and control datasets. |
| **`unexpected_difference`** | A numeric value that contains the unexpected difference between the segment's actual metric_test value and the segment's expected metric_test value, which is determined by comparing the ratio of change for this segment against the complement ratio of change. |
| **`relative_unexpected_difference`** | A numeric value that contains the ratio between the unexpected_difference value and the expected_metric_test value. |
| **`apriori_support`** | The proportion of the total metric in the test and control sets that this segment represents. |
| **`contribution`** | A numeric value that contains the absolute value of the difference value. |
---

## Example: Analyzing Revenue Change

```sql
-- 1. Create the model
CREATE OR REPLACE MODEL `my_project.my_dataset.revenue_analysis`
OPTIONS (
  MODEL_TYPE = 'CONTRIBUTION_ANALYSIS',
  is_test_col = 'is_current_year',
  dimension_id_cols = ['region', 'product_category', 'customer_segment'],
  contribution_metric = 'SUM(revenue)'
) AS
SELECT
  region,
  product_category,
  customer_segment,
  revenue,
  IF(date >= '2024-01-01', TRUE, FALSE) AS is_current_year
FROM
  `my_project.my_dataset.sales_data`;

-- 2. Get insights
SELECT
  *
FROM
  ML.GET_INSIGHTS(MODEL `my_project.my_dataset.revenue_analysis`)
ORDER BY
  unexpected_difference DESC;
```
ml_correlation.md 8.9 KB
# BigQuery ML.CORRELATION

`ML.CORRELATION` is a Table-Valued Function (TVF) that calculates the
statistical correlation between a target column and one or more target
correlation columns, optionally sliced by various dimensions.

## Syntax Reference

```sql
ML.CORRELATION(
  { TABLE TABLE_NAME | (QUERY_STATEMENT) },
  target_col => TARGET_COL,
  target_correlation_cols => TARGET_CORRELATION_COLS
  [, dimension_cols => DIMENSION_COLS ]
  [, method => METHOD ]
)
```

### Input Arguments

Argument                      | Requirement  | Type                        | Description
:---------------------------- | :----------- | :-------------------------- | :----------
**`input_data (positional)`** | **Required** |                             | The source table or query containing the data to analyze.
**`target_col`**              | **Required** | `STRING`                    | The name of the *numerical* column to be correlated.
**`target_correlation_cols`** | **Required** | `STRING` or `ARRAY<STRING>` | The name of the numerical columns to correlate against the `target_col`.
**`dimension_cols`**          | Optional     | `STRING` or `ARRAY<STRING>` | A value that contains the names of columns to slice the data by. The function calculates correlations for every combination of these dimensions (Max: 12 columns). Supported Types: Any Groupable data type. Unsupported: ARRAY, STRUCT, JSON, GEOGRAPHY.
**`method`**                  | Optional     | `STRING`                    | The correlation method: `PEARSON` (default), `SPEARMAN`, or `KENDALL`. The `KENDALL` method has O(N^2) performance implications on massive tables. For large datasets, it is highly recommended to use `PEARSON` or `SPEARMAN`.

**Note on Reserved Column Names:** The column names used in arguments must not
overlap with the reserved output column names: `segment`, `target_col`,
`corr_col`, `correlation`, `segment_size`, `segment_proportion`.

### Output Schema

| Column                   | Type                        | Description         |
| :----------------------- | :-------------------------- | :------------------ |
| **`segment`**            | `ARRAY<STRUCT<dimension_col | Identifies the      |
:                          : STRING, dimension_value     : specific            :
:                          : JSON>>`                     : combination of      :
:                          :                             : dimension names and :
:                          :                             : values used to      :
:                          :                             : group the data for  :
:                          :                             : this row.           :
| *`<dimension_cols>`*     | Varies                      | Columns             |
:                          :                             : corresponding to    :
:                          :                             : each dimension in   :
:                          :                             : `dimension_cols`.   :
| **`target_col`**         | `STRING`                    | The name of the     |
:                          :                             : target column.      :
| **`corr_col`**           | `STRING`                    | The name of the     |
:                          :                             : column being        :
:                          :                             : correlated against  :
:                          :                             : the target.         :
| **`correlation`**        | `FLOAT64`                   | The calculated      |
:                          :                             : correlation         :
:                          :                             : coefficient.        :
| **`segment_size`**       | `INT64`                     | The number of rows  |
:                          :                             : in the segment.     :
| **`segment_proportion`** | `FLOAT64`                   | A value that        |
:                          :                             : contains the        :
:                          :                             : fraction of total   :
:                          :                             : rows in the input   :
:                          :                             : table that belong   :
:                          :                             : to this segment.    :

**Note:** Results are sorted by `segment_size` (descending) and then `corr_col`
(ascending) by default.

## Examples

The following examples show how to use the `ML.CORRELATION` function and use the
`my_dataset.marketing_sample` table:

```sql
CREATE OR REPLACE TABLE my_dataset.marketing_sample AS (
  -- New York data
  SELECT 'USA' AS country, 'New York' AS city, 'Electronics' AS product_category, 100 AS ad_spend, 150 AS budget, 1000 AS revenue UNION ALL
  SELECT 'USA', 'New York', 'Electronics', 150, 200, 1500 UNION ALL
  SELECT 'USA', 'New York', 'Apparel',     200, 250, 2000 UNION ALL

  -- Seattle data
  SELECT 'USA', 'Seattle',  'Apparel',     200, 250, 2000 UNION ALL
  SELECT 'USA', 'Seattle',  'Apparel',     300, 350, 3000 UNION ALL

  -- London data (Genuine NULL country)
  SELECT NULL,  'London',   'Electronics', 100, 120, 500  UNION ALL
  SELECT NULL,  'London',   'Electronics', 200, 220, 900  UNION ALL

  -- Missing city data (Genuine NULL city)
  SELECT NULL,  NULL,       'Apparel',     200, 200, 1000 UNION ALL
  SELECT NULL,  NULL,       'Apparel',     250, 250, 1200
);


/*---------+----------+------------------+----------+---------+---------+
 | country | city     | product_category | ad_spend | budget  | revenue |
 +---------+----------+------------------+----------+---------+---------+
 | USA     | New York | Electronics      | 100      | 150     | 1000    |
 | USA     | New York | Electronics      | 150      | 200     | 1500    |
 | USA     | New York | Apparel          | 200      | 250     | 2000    |
 | USA     | Seattle  | Apparel          | 200      | 250     | 2000    |
 | USA     | Seattle  | Apparel          | 300      | 350     | 3000    |
 | null    | London   | Electronics      | 100      | 120     | 500     |
 | null    | London   | Electronics      | 200      | 220     | 900     |
 | null    | null     | Apparel          | 200      | 200     | 1000    |
 | null    | null     | Apparel          | 250      | 250     | 1200    |
 +---------+----------+------------------+----------+---------+---------*/
```

### Calculate Pearson correlation

The following example calculates the Pearson correlation between `revenue` and
`ad_spend` from the table `my_dataset.marketing_sample` and uses `country` as a
dimension column:

```sql
SELECT
  country,
  segment,
  correlation,
  segment_size
FROM ML.CORRELATION(
  TABLE my_dataset.marketing_sample,
  target_col => 'revenue',
  target_correlation_cols => 'ad_spend',
  dimension_cols => ['country']
);

/*---------+---------------------------------------------------------------+-------------+--------------+
 | country | segment                                                       | correlation | segment_size |
 +---------+---------------------------------------------------------------+-------------+--------------+
 | 'USA'   | [{dimension_col: 'country', dimension_value: 'USA'}] | 1.0         | 2            |
 | NULL    | [{dimension_col: 'country', dimension_value: null}]  | 1.0         | 2            |
 | NULL    | []                                                            | 0.688       | 4            |
 +---------+---------------------------------------------------------------+-------------+--------------*/
```

The second row of the result corresponds to a genuine `NULL` in the input data
for country because the `dimension_value` field is `NULL`. The third row of the
result contains `NULL` for country because it corresponds to aggregation over
all countries.

### Calculate correlation for multiple columns

The following example calculates the correlation between `revenue` and
`ad_spend` and `budget`, sliced by `city` and `product_category`, from the table
`my_dataset.marketing_sample`:

```sql
SELECT *
FROM
ML.CORRELATION(
 (SELECT * FROM my_dataset.marketing_sample WHERE country = 'USA'),
 target_col => 'revenue',
 target_correlation_cols => ['ad_spend', 'budget'],
 dimension_cols => ['city', 'product_category']
);
```

### Distinguish between global aggregates and missing data

The following example shows how to use the `segment` column to label your rows
clearly in a report:

```sql
SELECT
  -- Create a clean label for reporting
  CASE
    -- If 'city' is NULL and not in the segment array, it's a total
    WHEN city IS NULL AND NOT EXISTS(SELECT 1 FROM UNNEST(segment) s WHERE s.dimension_col = 'city')
      THEN 'ALL CITIES (Global)'
    -- If 'city' is NULL and in the segment array, it's missing data
    WHEN city IS NULL
      THEN 'UNKNOWN CITY'
    ELSE city
  END AS city_label,
  correlation,
  segment_size
FROM ML.CORRELATION(
  TABLE my_dataset.marketing_sample,
  target_col => 'revenue',
  target_correlation_cols => 'ad_spend',
  dimension_cols => ['city']
);
```
ml_describe_data.md 5.1 KB
# BigQuery ML.DESCRIBE_DATA

`ML.DESCRIBE_DATA` generates descriptive statistics for the columns in a table
or subquery.

## Syntax Reference

```sql
SELECT
  *
FROM
  ML.DESCRIBE_DATA(
    { TABLE project.dataset.table | (QUERY_STATEMENT) },
    STRUCT(
      [NUM_QUANTILES AS num_quantiles]
      [, NUM_ARRAY_LENGTH_QUANTILES AS num_array_length_quantiles]
      [, TOP_K AS top_k])
  )
```

### Input Arguments

Argument                         | Requirement  | Type    | Description
:------------------------------- | :----------- | :------ | :----------
**`input_data`**                 | **Required** |         | The source table or subquery containing the data to analyze.
**`NUM_QUANTILES`**              | Optional     | `INT64` | Specifies the number of quantiles to return for numerical, `ARRAY<numerical>`, and `ARRAY<STRUCT<INT64, numerical>>` columns. This affects the number of results shown in the quantiles output column. These quantiles describe the distribution of the data in the column. Specify a lower value for coarser-grained distribution information and a higher value for finer-grained distribution information. The NUM_QUANTILES value must be in the range [1, 100,000]. The default value is 2.
**`NUM_ARRAY_LENGTH_QUANTILES`** | Optional     | `INT64` | Specifies the number of quantiles to return for ARRAY columns. This affects the number of results shown in the array_length_quantiles output column. These quantiles describe the distribution of the length of the arrays in the column. Specify a lower value for coarser-grained distribution information and a higher value for finer-grained distribution information. The NUM_ARRAY_LENGTH_QUANTILES value must be in the range [1, 100,000]. The default value is 10.
**`TOP_K`**                      | Optional     | `INT64` | Specifies the number of top values to return for categorical and `ARRAY<categorical>` columns. This affects the number of results shown in the top_values output column. The top values are the values that are shown most frequently in the column. The TOP_K value must be in the range [1, 10,000]. The default value is 1.

Input data for the `ML.DESCRIBE_DATA` function can only contain columns of the
following data types: Numeric types, `STRING`, `BOOL`, `BYTES`, `DATE`,
`DATETIME`, `TIME`, `TIMESTAMP`. It also supports `ARRAY` columns or `STRUCT`
columns that contain any of the previous primitive types. Columns with
unsupported data types, such as `GEOGRAPHY`, must be excluded from the input
data.

### Output Schema

Returns a table with one row per input column with the following fields:

Column Name                  | Type                           | Description
:--------------------------- | :----------------------------- | :----------
**`name`**                   | `STRING`                       | The name of the input column.
**`num_rows`**               | `INT64`                        | The total number of rows for the input column.
**`num_nulls`**              | `INT64`                        | The number of NULL values found in the column.
**`num_zeros`**              | `INT64`                        | The number of 0 values found in the column.
**`min`**                    | `STRING`                       | The MIN value for the numerical column.
**`max`**                    | `STRING`                       | The MAX value for the numerical column.
**`mean`**                   | `FLOAT64`                      | The Mean value for the numerical column.
**`stddev`**                 | `FLOAT64`                      | The standard deviation value calculated for the numerical column.
**`median`**                 | `FLOAT64`                      | The median value calculated for the numerical column.
**`quantiles`**              | `ARRAY<FLOAT64>`               | The quantiles in an input column.
**`unique`**                 | `INT64`                        | The number of unique values in an input column.
**`avg_string_length`**      | `FLOAT64`                      | The average length of the values in the categorical column.
**`num_values`**             | `INT64`                        | The number of array elements for ARRAY columns, and the number of values in the column for other types of columns.
**`top_values`**             | `ARRAY<STRUCT<STRING, INT64>>` | The top values and number of occurrences in an input column
**`min_array_length`**       | `INT64`                        | The minimum length of an array in the column.
**`max_array_length`**       | `INT64`                        | The maximum length of an array in the column.
**`avg_array_length`**       | `FLOAT64`                      | The average length of arrays in the column.
**`total_array_length`**     | `INT64`                        | The sum of the size of the arrays in the column.
**`array_length_quantiles`** | `ARRAY<INT64>`                 | The quantiles for the array length in an input column, as computed by the APPROX_QUANTILES function.
**`dimension`**              | `INT64`                        | The dimension of array elements for ARRAY columns.

## Examples

### Calculate statistics for a table

```sql
SELECT *
FROM ML.DESCRIBE_DATA(
  TABLE `bigquery-public-data.ml_datasets.penguins`
);
```
ml_detect_change_points.md 5.5 KB
# BigQuery ML.Detect_Change_Points

`ML.DETECT_CHANGE_POINTS` is a one-step Table-Valued Function (TVF) that
identifies intervals where the statistical behavior of time series data have
shifted. It distinguishes structural breaks (e.g. "slow bleed" anomalies,
sustained structural shifts) from transient or isolated events. All identified
change points are represented as time windows defined by both a beginning and an
ending timestamp.

## Syntax Reference

```sql
SELECT
  *
FROM
  ML.DETECT_CHANGE_POINTS(
    { TABLE `project.dataset.table` | (QUERY_STATEMENT) },
    data_col => 'DATA_COL',
    timestamp_col => 'TIMESTAMP_COL'
    [, id_cols => ID_COLS]
  )
```

### Input Arguments

| Argument            | Requirement  | Type          | Description             |
| :------------------ | :----------- | :------------ | :---------------------- |
| **`input_data`**    | **Required** |               | The source table or     |
:                     :              :               : query containing        :
:                     :              :               : historical time series  :
:                     :              :               : data.                   :
| **`data_col`**      | **Required** | String        | The name of the numeric |
:                     :              :               : column in `input_data`  :
:                     :              :               : to analyze. The data    :
:                     :              :               : column must use one of  :
:                     :              :               : the following data      :
:                     :              :               : types\: `INT64`,        :
:                     :              :               : `FLOAT64`, `NUMERIC`,   :
:                     :              :               : `BIGNUMERIC`.           :
| **`timestamp_col`** | **Required** | String        | The name of the         |
:                     :              :               : date/timestamp column   :
:                     :              :               : in `input_data`. The    :
:                     :              :               : timestamp column must   :
:                     :              :               : use one of the          :
:                     :              :               : following data types\:  :
:                     :              :               : `DATE`, `DATETIME`,     :
:                     :              :               : `TIMESTAMP`.            :
| **`id_cols`**       | Optional     | Array<String> | The names of the        |
:                     :              :               : grouping columns for    :
:                     :              :               : multiple time series    :
:                     :              :               : (e.g., `['store_id']`). :
:                     :              :               : The columns that you    :
:                     :              :               : specify must use one of :
:                     :              :               : the following data      :
:                     :              :               : types\: `STRING`,       :
:                     :              :               : `INT64`,                :
:                     :              :               : `ARRAY<STRING>`,        :
:                     :              :               : `ARRAY<INT64>`.         :

### Output Schema

| Column                | Type       | Description                             |
| :-------------------- | :--------- | :-------------------------------------- |
| **`id_cols`**         | (As Input) | Original identifiers for the time       |
:                       :            : series.                                 :
| **`begin_timestamp`** | TIMESTAMP  | Timestamp corresponding to the start of |
:                       :            : the change point.                       :
| **`end_timestamp`**   | TIMESTAMP  | Timestamp corresponding to the end of   |
:                       :            : the change point.                       :
| **`metrics`**         | STRUCT     | A set of metrics describing the         |
:                       :            : statistical behavior.                   :
| **`metrics.avg`**     | FLOAT64    | Calculated average metric value within  |
:                       :            : this change point.                      :
| **`metrics.min`**     | FLOAT64    | Minimum metric value observed.          |
| **`metrics.max`**     | FLOAT64    | Maximum metric value observed.          |
| **`metrics.stddev`**  | FLOAT64    | Standard deviation within this change   |
:                       :            : point.                                  :
| **`metrics.count`**   | INT64      | Total count of data points in the       |
:                       :            : identified change point.                :
| **`status`**          | STRING     | Error messages or empty string on       |
:                       :            : success.                                :

## Examples

### Detecting Change Points in Taxi Trips

This example detects structural shifts in the number of New York taxi trips
spanning 2019 to 2020:

```sql
WITH daily_trips AS (
  SELECT
    EXTRACT(DATE FROM pickup_datetime) AS trip_date,
    COUNT(*) AS total_trips
  FROM
    `bigquery-public-data.new_york_taxi_trips.tlc_yellow_trips_20*`
  WHERE
    _TABLE_SUFFIX BETWEEN '19' AND '20'
    AND EXTRACT(DATE FROM pickup_datetime) BETWEEN '2019-01-01' AND '2020-12-31'
  GROUP BY
    trip_date
)
SELECT
  *
FROM
  ML.DETECT_CHANGE_POINTS(
    TABLE daily_trips,
    data_col => 'total_trips',
    timestamp_col => 'trip_date'
  );
```
ml_seasonality.md 6.6 KB
# BigQuery ML.Seasonality

`ML.SEASONALITY` is a time-series decomposition function that extracts seasonal
components to decouple recurring patterns from the underlying trend and noise.

## Syntax Reference

```sql
SELECT
  *
FROM
  ML.SEASONALITY(
    { TABLE `project.dataset.table` | (QUERY_STATEMENT) },
    data_col => 'DATA_COL',
    timestamp_col => 'TIMESTAMP_COL'
    [, id_cols => ID_COLS]
    [, seasonalities => SEASONALITIES]
    [, horizon => HORIZON]
  )
```

### Input Arguments

| Argument            | Requirement  | Type          | Description             |
| :------------------ | :----------- | :------------ | :---------------------- |
| **`input_data`**    | **Required** |               | The source table or     |
:                     :              :               : query containing        :
:                     :              :               : historical time series  :
:                     :              :               : data.                   :
| **`data_col`**      | **Required** | String        | The name of the numeric |
:                     :              :               : column in `input_data`. :
:                     :              :               : Supported types\:       :
:                     :              :               : `INT64`, `FLOAT64`,     :
:                     :              :               : `NUMERIC`,              :
:                     :              :               : `BIGNUMERIC`.           :
| **`timestamp_col`** | **Required** | String        | The name of the         |
:                     :              :               : date/timestamp column   :
:                     :              :               : in `input_data`.        :
:                     :              :               : Supported types\:       :
:                     :              :               : `DATE`, `DATETIME`,     :
:                     :              :               : `TIMESTAMP`.            :
| **`id_cols`**       | Optional     | Array<String> | The names of the        |
:                     :              :               : grouping columns for    :
:                     :              :               : multiple series (e.g.,  :
:                     :              :               : `['store_id']`).        :
:                     :              :               : Supported types\:       :
:                     :              :               : `STRING`, `INT64`,      :
:                     :              :               : `ARRAY<STRING>`,        :
:                     :              :               : `ARRAY<INT64>`.         :
| **`seasonalities`** | Optional     | Array<String> | Seasonality types to    |
:                     :              :               : extract. Valid values\: :
:                     :              :               : `Yearly`, `Quarterly`,  :
:                     :              :               : `Monthly`, `Weekly`,    :
:                     :              :               : `Daily`. If omitted,    :
:                     :              :               : the function            :
:                     :              :               : automatically detects   :
:                     :              :               : all seasonalities.      :
| **`horizon`**       | Optional     | Int64         | Number of future time   |
:                     :              :               : points to forecast.     :
:                     :              :               : Default is `0` (history :
:                     :              :               : only). Range `[1,       :
:                     :              :               : 10,000]`.               :

### Output Schema

| Column                 | Type       | Description                            |
| :--------------------- | :--------- | :------------------------------------- |
| **`id_cols`**          | (As Input) | Original identifiers for the series.   |
| **`[timestamp_col]`**  | (As Input) | The column name and type match the     |
:                        :            : input column specified in              :
:                        :            : *TIMESTAMP_COL*.                       :
| **`[data_col]`**       | FLOAT64    | The column name matches the input      |
:                        :            : column specified in *DATA_COL*. For    :
:                        :            : 'history' rows, this contains the      :
:                        :            : training data (automatically           :
:                        :            : interpolated to resolve any missing    :
:                        :            : points). For 'forecast' rows, it       :
:                        :            : contains the forecast value.           :
| **`time_series_type`** | STRING     | Label: `'history'` or `'forecast'`.    |
| **`yearly`**           | FLOAT64    | Calculated yearly seasonal component.  |
:                        :            : A NULL value means no yearly           :
:                        :            : seasonality detected.                  :
| **`quarterly`**        | FLOAT64    | Calculated quarterly seasonal          |
:                        :            : component. A NULL value means no       :
:                        :            : quarterly seasonality detected.        :
| **`monthly`**          | FLOAT64    | Calculated monthly seasonal component. |
:                        :            : A NULL value means no monthly          :
:                        :            : seasonality detected.                  :
| **`weekly`**           | FLOAT64    | Calculated weekly seasonal component.  |
:                        :            : A NULL value means no weekly           :
:                        :            : seasonality detected.                  :
| **`daily`**            | FLOAT64    | Calculated daily seasonal component. A |
:                        :            : NULL value means no daily seasonality  :
:                        :            : detected.                              :
| **`status`**           | STRING     | Error messages or empty string on      |
:                        :            : success. A minimum of 3 data points is :
:                        :            : required.                              :

## Examples

### Analyzing Seasonality in Daily Visits

This example analyzes the daily website visits from Google Analytics session
data:

```sql
WITH DailyVisits AS (
  SELECT
    PARSE_TIMESTAMP('%Y%m%d', date) AS visit_timestamp,
    SUM(totals.visits) AS total_visits
  FROM
    `bigquery-public-data.google_analytics_sample.ga_sessions_*`
  GROUP BY
    visit_timestamp
)
SELECT
  *
FROM
  ML.SEASONALITY(
    TABLE DailyVisits,
    data_col => 'total_visits',
    timestamp_col => 'visit_timestamp'
  );
```
ml_trend.md 4.1 KB
# BigQuery ML.Trend

`ML.TREND` is a time-series decomposition function that extracts the underlying
long-term direction of data, isolating the persistent growth or decline from
seasonal fluctuations and random noise without requiring a pre-trained model.

## Syntax Reference

```sql
SELECT
  *
FROM
  ML.TREND(
    { TABLE `project.dataset.table` | (QUERY_STATEMENT) },
    data_col => 'DATA_COL',
    timestamp_col => 'TIMESTAMP_COL'
    [, id_cols => ID_COLS]
    [, horizon => HORIZON]
    [, smoothing_window_size => SMOOTHING_WINDOW_SIZE]
    [, adjust_step_changes => ADJUST_STEP_CHANGES]
  )
```

### Input Arguments

Argument                    | Requirement  | Type          | Description
:-------------------------- | :----------- | :------------ | :----------
**`input_data`**            | **Required** |               | The source table or query containing historical time series data.
**`data_col`**              | **Required** | String        | The name of the numeric column in `input_data`. Supported types: `INT64`, `FLOAT64`, `NUMERIC`, `BIGNUMERIC`.
**`timestamp_col`**         | **Required** | String        | The name of the date/timestamp column in `input_data`. Supported types: `DATE`, `DATETIME`, `TIMESTAMP`.
**`id_cols`**               | Optional     | Array<String> | The names of the grouping columns for multiple series (e.g., `['store_id']`). Supported types: `STRING`, `INT64`, `ARRAY<STRING>`, `ARRAY<INT64>`.
**`horizon`**               | Optional     | Int64         | Number of future time points to forecast. Default is `0` (historical trend only). Range `[1, 10,000]`.
**`smoothing_window_size`** | Optional     | Int64         | Size of the center moving average smoothing window used to smooth out noise before trend extraction. Default is `5`. Must be positive.
**`adjust_step_changes`**   | Optional     | Bool          | Whether to perform automatic step change detection and adjustment. When true, identifies abrupt level shifts and blends their impact into the surrounding data before extracting the trend, generating a smoother, more continuous result.

### Output Schema

| Column                 | Type       | Description                            |
| :--------------------- | :--------- | :------------------------------------- |
| **`id_cols`**          | (As Input) | Original identifiers for the series.   |
| **`[timestamp_col]`**  | (As Input) | The column name and type match the     |
:                        :            : input column specified in              :
:                        :            : *TIMESTAMP_COL*.                       :
| **`[data_col]`**       | FLOAT64    | The column name matches the input      |
:                        :            : column specified in *DATA_COL*. For    :
:                        :            : 'history' rows, this contains the      :
:                        :            : training data (automatically           :
:                        :            : interpolated to resolve any missing    :
:                        :            : points). For 'forecast' rows, it       :
:                        :            : contains the forecast value.           :
| **`time_series_type`** | STRING     | Label: `'history'` or `'forecast'`.    |
| **`trend`**            | FLOAT64    | The calculated trend component for the |
:                        :            : time point.                            :
| **`status`**           | STRING     | Error messages or empty string on      |
:                        :            : success. A minimum of 3 data points is :
:                        :            : required.                              :

## Examples

### Analyzing Trends in Daily Visits

This example analyzes the daily visit trend from Google Analytics sample data:

```sql
WITH DailyVisits AS (
  SELECT
    PARSE_TIMESTAMP('%Y%m%d', date) AS visit_timestamp,
    SUM(totals.visits) AS total_visits
  FROM
    `bigquery-public-data.google_analytics_sample.ga_sessions_*`
  GROUP BY
    visit_timestamp
)
SELECT
  *
FROM
  ML.TREND(
    TABLE DailyVisits,
    data_col => 'total_visits',
    timestamp_col => 'visit_timestamp'
  );
```
remote_models.md 1.1 KB
# Creating Remote Models
Generative and embedding functions require a remote model that points to a
specific endpoint (e.g., Gemini). Remote models are created using a connection
to interact with Vertex AI.

### Syntax

```sql
CREATE [OR REPLACE] MODEL `project.dataset.model_name`
REMOTE WITH CONNECTION { DEFAULT | `project.region.connection_id` }
OPTIONS (ENDPOINT = 'endpoint_name');
```

### Available Endpoints

BigQuery supports the following models:

*   **Generative**:
    *   `gemini-3.1-flash-lite`
    *   `gemini-3.5-flash`
    *   `gemini-3.5-flash-lite`
    *   `gemini-3.6-flash`
    *   `gemini-3.7-flash`
    *   `gemini-3.8-flash`
    *   `gemini-4-argon`
*   **Embedding**: `text-embedding-005`, `text-multilingual-embedding-002`,
    `gemini-embedding-001`, `gemini-embedding-2`.

### Connection Usage
If `REMOTE WITH CONNECTION DEFAULT` is used, BigQuery automatically attempts to
use a default connection in the model's region. Default connection should be
the default behavior. Otherwise, you must specify a fully qualified connection
ID (e.g., `my-project.us.my-connection`).
vector_search.md 4.0 KB
# VECTOR_SEARCH

BigQuery `VECTOR_SEARCH` is a table-valued function used to find semantically
similar entities by searching embeddings in a base table against embeddings in a
query table.

## Syntax

```sql
VECTOR_SEARCH(
  { TABLE base_table | (base_table_query) },
  column_to_search,
  { TABLE query_table | (query_table_query) },
  [, query_column_to_search => query_column_to_search_value]
  [, top_k => top_k_value ]
  [, distance_type => distance_type_value ]
  [, options => options_value ]
)
```

### Arguments
| Argument | Requirement | Type | Description |
| :--- | :--- | :--- | :--- |
| **`base_table`** | **One Of**  | TABLE | The table containing the embeddings to search. Mutually exclusive with base_table_query. |
| **`base_table_query`** | **One Of** | QUERY | A query that you can use to pre-filter the base table. Only SELECT, FROM, and WHERE clauses are allowed in this query. Don't apply any filters to the embedding column. Mutually exclusive with base_table. |
| **`column_to_search`** | **Required** | String | The name of the base table column containing embeddings (`ARRAY<FLOAT64>` or `STRING`). |
| **`query_table`** | **One Of**  | TABLE | The table that provides the embeddings for which to find nearest neighbors. All columns are passed through as output columns. Mutually exclusive with query_table_query |
| **`query_table_query`** | **One Of**  | QUERY | A query that provides the embeddings for which to find nearest neighbors. All columns are passed through as output columns. Mutually exclusive with query_table |
| **`query_column_to_search`** | Optional | String | The name of the column in the query table. Defaults to `column_to_search`. The value can be either `STRING` or `ARRAY<FLOAT64>`. If `STRING`, the base_table must have autonomous embedding generation enabled. The string values are embedded at runtime using the same connection and endpoint specified for the base table's embedding generation. If the value is an `ARRAY<FLOAT64>`, all elements in the array must be non-NULL and all values in the column must have the same array dimensions as the values in the column_to_search column.|
| **`top_k`** | Optional | Int64 | The number of nearest neighbors to return. Defaults to 10. |
| **`distance_type`** | Optional | String | The metric to use: `'EUCLIDEAN'`, `'COSINE'`, or `'DOT_PRODUCT'`. Defaults to `'EUCLIDEAN'`. |
| **`options`** | Optional | String | JSON string for search options (e.g., `use_brute_force`, `fraction_lists_to_search`). |

### Output Columns
| Column | Type | Description |
| :--- | :--- | :--- |
| **`base`** | STRUCT | A STRUCT value that contains all columns from base_table or a subset of the columns from base_table that you selected in the base_table_query query. |
| **`query`** | STRUCT | A STRUCT value that contains all selected columns from the query data. This column is only included in the output if you use the batch search syntax. For single vector searches, this column is omitted.|
| **`distance`** | FLOAT64 | A FLOAT64 value that represents the distance between the base data and the query data. |

---

## Example: Combined Vector Search with AI.GENERATE_EMBEDDING

```sql
SELECT
  query.content AS search_query,
  base.product_name,
  base.description,
  distance
FROM
  VECTOR_SEARCH(
    TABLE `my_project.my_dataset.products`,
    'product_embedding',
    (
      SELECT
        content,
        embedding
      FROM
        AI.GENERATE_EMBEDDING(
          MODEL `my_project.my_dataset.embedding_model`,
          (SELECT "high-performance running shoes" AS content)
        )
    ),
    top_k => 5,
    distance_type => 'COSINE'
  );
```

---

## Example: Optimized Single Search

This version is optimized for finding neighbors for a single value.

```sql
SELECT
  base.product_name,
  base.description,
  distance
FROM
  VECTOR_SEARCH(
    TABLE `my_project.my_dataset.products`,
    'product_embedding',
    query_value => (
      SELECT embedding
      FROM AI.GENERATE_EMBEDDING(
        MODEL `my_project.my_dataset.embedding_model`,
        (SELECT "high-performance running shoes" AS content)
      )
    ),
    top_k => 5
  );
```

License (Apache-2.0)

View full license text
Licensed under the Apache License, Version 2.0. See https://github.com/google/skills/blob/main/LICENSE