Use AI functions in dynamic tables

AI function calls may cost significantly more than most SQL operations. For more information, see Cost considerations for Cortex AI Functions. When a dynamic table calls AI functions, use REFRESH_MODE = CUSTOM_INCREMENTAL so that Snowflake calls the function only for new rows and for rows whose AI input changed. Avoid calling AI functions in the definition of a SELECT-based dynamic table.

Choose a pattern

Both patterns use a custom incremental dynamic table that calls the AI function and stores the result. Choose the pattern that matches how rows in the base table change:

Rows in the base tablePatternExample
Are only added, never updated or deletedINSERT INTO SELF with CHANGES(INFORMATION => APPEND_ONLY)Example: insert-only
Can be inserted, updated, or deleted, and have a stable unique keyMERGE INTO SELF that compares each change with the stored rowExample: update and delete rows with a stable key

Create the base table

The examples on this page use the following base table of support tickets:

CREATE OR REPLACE TABLE raw_tickets (
  ticket_id INT,
  ticket_text STRING,
  status STRING,
  created_at TIMESTAMP_NTZ
) CHANGE_TRACKING = TRUE;

Example: insert-only

If rows are only added to the base table, use INSERT INTO SELF with CHANGES(INFORMATION => APPEND_ONLY). Snowflake calls the AI function once for each new row and never revisits existing rows.

CREATE OR ALTER DYNAMIC TABLE dt_ticket_categories_ai (
  ticket_id INT,
  ticket_text STRING,
  raw_category VARIANT,
  ai_fn STRING,
  ai_at TIMESTAMP_LTZ
)
  TARGET_LAG = '1 hour'
  WAREHOUSE = transform_wh
  REFRESH_MODE = CUSTOM_INCREMENTAL
  REFRESH USING (
    INSERT INTO SELF
    SELECT
      ticket_id,
      ticket_text,
      AI_CLASSIFY(COALESCE(ticket_text, ''), ['billing', 'technical', 'account', 'other']),
      'classify:v1',
      CURRENT_TIMESTAMP()
    FROM raw_tickets CHANGES(INFORMATION => APPEND_ONLY)
    ORDER BY ticket_id
  );

The ai_fn column labels the version of the AI function call that produced each row, and ai_at records when the call ran. Because APPEND_ONLY returns inserts only, updates and deletes in raw_tickets are ignored.

Example: update and delete rows with a stable key

If rows in the base table can be updated or deleted, use MERGE INTO SELF. The following definition calls the AI function only when a ticket is new or when ticket_text changes. When only status changes, Snowflake updates the stored row without calling the function.

CREATE OR ALTER DYNAMIC TABLE dt_tickets_ai (
  ticket_id INT,
  ticket_text STRING,
  status STRING,
  raw_category VARIANT,
  ai_fn STRING,
  ai_at TIMESTAMP_LTZ
)
  TARGET_LAG = '1 hour'
  WAREHOUSE = transform_wh
  REFRESH_MODE = CUSTOM_INCREMENTAL
  REFRESH USING (
    MERGE INTO SELF AS t
    USING (
      -- 1. Source and consolidation: keep one change row for each ticket_id.
      -- The INSERT row wins over the DELETE row, so an update arrives as one row.
      SELECT ticket_id, ticket_text, status, METADATA$ACTION AS action
      FROM raw_tickets CHANGES(INFORMATION => DEFAULT)
      QUALIFY ROW_NUMBER() OVER (
        PARTITION BY ticket_id
        ORDER BY IFF(METADATA$ACTION = 'INSERT', 0, 1)
      ) = 1
      ORDER BY ticket_id
    ) AS s
    -- 2. Match on the key.
    ON t.ticket_id = s.ticket_id
    -- 3a. The ticket was deleted: delete the stored row.
    WHEN MATCHED AND s.action = 'DELETE' THEN DELETE
    -- 3b. The ticket is new: call the AI function.
    WHEN NOT MATCHED AND s.action = 'INSERT' THEN INSERT
      (ticket_id, ticket_text, status, raw_category, ai_fn, ai_at)
      VALUES (
        s.ticket_id, s.ticket_text, s.status,
        AI_CLASSIFY(COALESCE(s.ticket_text, ''), ['billing', 'technical', 'account', 'other']),
        'classify:v1', CURRENT_TIMESTAMP()
      )
    -- 3c. The AI input changed: update every column and call the AI function again.
    WHEN MATCHED AND s.action = 'INSERT'
      AND NOT EQUAL_NULL(s.ticket_text, t.ticket_text) THEN UPDATE SET
        ticket_text = s.ticket_text,
        status = s.status,
        raw_category = AI_CLASSIFY(COALESCE(s.ticket_text, ''), ['billing', 'technical', 'account', 'other']),
        ai_fn = 'classify:v1',
        ai_at = CURRENT_TIMESTAMP()
    -- 3d. Only a non-AI column changed: update it in place, without calling the AI function.
    WHEN MATCHED AND s.action = 'INSERT'
      AND NOT EQUAL_NULL(s.status, t.status) THEN UPDATE SET
        status = s.status
  );

Create a SELECT-based dynamic table downstream to extract typed columns from the raw result. Changing this definition later doesn’t call the AI function again.

CREATE OR ALTER DYNAMIC TABLE dt_tickets
  TARGET_LAG = '1 hour'
  WAREHOUSE = transform_wh
  REFRESH_MODE = INCREMENTAL
  AS
    SELECT
      ticket_id,
      ticket_text,
      status,
      raw_category:labels[0]::STRING AS category
    FROM dt_tickets_ai;

Parts of the MERGE definition

The numbers in the following list match the comments in the definition of dt_tickets_ai.

  1. Source and consolidation. CHANGES(INFORMATION => DEFAULT) returns each change as an INSERT or DELETE row. An update appears as a DELETE and INSERT pair, and so does a base table that’s rewritten with identical data. The QUALIFY clause keeps one row for each key: the INSERT row if one exists, otherwise the DELETE row. The ORDER BY clause lays out the table by key, which keeps later refreshes small.
  2. Match. ON matches each change to the stored row with the same key.
  3. Clauses. Snowflake evaluates the WHEN clauses in order and runs the first one that matches. The following table describes each clause:
ClauseRuns whenCalls the AI function
3aThe key was deleted from the base table.No
3bThe key is new.Yes
3cThe key exists and an AI input column differs from the stored row.Yes
3dThe key exists, the AI input is unchanged, and another column differs from the stored row.No

If the base table is rewritten with identical data, or an update leaves every column unchanged, no clause matches and the refresh doesn’t write any rows.

Pipeline structure

The examples on this page use two kinds of dynamic tables:

  • A custom incremental dynamic table calls the AI function. It’s the only dynamic table in the pipeline that calls AI functions. It stores the raw result in a VARIANT column, along with the other columns that downstream tables need.
  • A SELECT-based dynamic table reads the custom incremental dynamic table and extracts the typed columns from the raw result. Joins, filters, and aggregations also belong in SELECT-based dynamic tables.

Guidelines

  • Use a key that’s unique across all rows that feed the table and that doesn’t change when a row is rewritten, such as an ID column. If two rows have the same key, the stored row is overwritten and the AI function is called again.
  • Compare only the columns that you pass to the AI function in the AI-input clause (3c). Compare every other column in the non-AI clause (3d). Set every column in the INSERT clause and in the AI-input UPDATE clause.
  • Use EQUAL_NULL to compare values. A comparison with <> returns NULL when either value is NULL, so a change to or from NULL is missed.
  • Store the raw result as VARIANT and extract typed columns in a downstream SELECT-based dynamic table. You can’t change the type of a column in a custom incremental dynamic table later.
  • Write the AI function call only in the INSERT clause and the AI-input UPDATE clause, with identical arguments in both. Use COALESCE on prompt arguments that can be NULL.
  • Use CREATE OR ALTER to change the definition. CREATE OR REPLACE discards the stored results, and the next refresh calls the AI function for every row.
  • To change the model or prompt, update the function call in both clauses with CREATE OR ALTER and change the ai_fn label. Existing rows keep their results. Only new rows and rows with a changed AI input use the new call.
  • Make sure change tracking is enabled on the base table, and that its data retention period is longer than the longest gap between refreshes. For more information, see Usage notes.
  • To clean up stored AI results that you no longer need, use a storage lifecycle policy. For more information, see Use storage lifecycle policies with dynamic tables.

Verify AI function calls

Rows that the AI function processed in a refresh have a recent ai_at value. To see how many rows each version of the call produced, and when the function last ran, query the custom incremental dynamic table:

SELECT ai_fn, COUNT(*) AS row_count, MAX(ai_at) AS latest_ai_call
  FROM dt_tickets_ai
  GROUP BY ai_fn;

To see how many rows each refresh inserted and deleted, query the DYNAMIC_TABLE_REFRESH_HISTORY function.

Limitations

Custom incremental dynamic tables have the limitations described in Limitations. For example, you can’t use dbt to manage them.

What’s next