The companion piece for the people actually writing the SQL.
As noted in AISQL isn’t BI With AI – It’s Data Science in SQL Clothing:
AI functions look like SQL, but the discipline they require is borrowed from data science.
This guide outlines practical strategies for building AI analytics pipelines in Snowflake while optimizing for cost, performance, and reliability.
Most of what follows comes back to the same three themes:
The sections below are practical patterns for working within these three constraints.
The single highest-leverage thing to do is hand-label a few hundred rows of ground truth before writing a single AI function call. This is your eval set. It’s the equivalent of unit tests for a deterministic pipeline.
Select 200–500 rows that are representative of what production looks like. This set should include the obvious cases, the ambiguous middle, and and edge cases—such as sarcasm, multi-topic inputs, or complex scenarios—that are known to be critical for your business. Label them yourself or with a domain expert and store them in a regular Snowflake table:
CREATE TABLE eval_set_tickets (
ticket_id STRING,
ticket_text STRING,
true_category STRING,
true_sentiment STRING,
notes STRING -- why this case is interesting
);
This table is a foundational asset for your AI pipeline. It should be versioned, backed up, and expanded whenever production data reveals new edge cases.
The workflow from here is: running the AI functions on the eval set, comparison to ground truth and observing errors. Only scaling to the full dataset once the business threshold has been hit on the eval set.
A single SELECT against 500 rows costs cents. The same logic against five million rows costs real money. That gap is the main reason you build the eval set first.
-- Run the function and compare
SELECT
ticket_id,
true_category,
AI_CLASSIFY(ticket_text, ['bug', 'billing', 'feature_request', 'other']):labels[0]::STRING AS predicted_category,
CASE WHEN true_category = predicted_category THEN 1 ELSE 0 END AS correct
FROM eval_set_tickets;
Before going further it’s worth dwelling on what “accuracy” actually means here, because the instinct most analytics engineers bring from traditional SQL is misleading. In deterministic SQL, a row is either right or wrong – the test passes or it doesn’t. In AI analytics, that framing falls apart. Two errors with the same headline cost (one row wrong) can have wildly different business cost. Some errors are routing inconveniences. Others are missed business opportunities.
Take a classifier that scores incoming support tickets into Critical, High, Medium, Low. You run it on a 1,000-row eval set and the headline is great: 87% overall accuracy. That looks good enough to ship it, but look at the confusion matrix first.

The model handles High, Medium, and Low well. It even gets most Critical tickets right. But looking at the highlighted cell: 23 truly Critical tickets got sent to the Medium queue.
After investigation the conclusion is they are almost all payment-related – failed charges, billing disputes, subscription issues. The model treated them like routine billing tickets because, on the surface, they look like routine billing tickets. The Medium queue has a 72-hour SLA. By the time those tickets get touched, the customer has already churned.
The other errors elsewhere in the matrix are mostly noise – a High ticket landing in Critical, a Low ticket landing in Medium, things a human reroutes in seconds. The 23 errors in that one cell are real money walking out the door.
An 87% model that fails specifically on payment urgency is worse than a 78% model that fails evenly across the matrix.
The fix is rarely “make the model more accurate.” The fix is encoding the business logic the model can’t infer from the text alone. A payment dispute from a self-serve free user might genuinely be Medium. The same dispute from a $200K-a-year enterprise account is Critical, every time. The text doesn’t tell the model that. Your data does.
A simple change – passing a customer-tier flag into the prompt, or applying a deterministic rule on top of the model output – would catch most of those 23 cases:
SELECT
ticket_id,
-- Encode the business rule alongside the model
CASE
WHEN customer_tier = 'enterprise'
AND AI_CLASSIFY(ticket_text, ['payment','other']):labels[0]::STRING = 'payment'
THEN 'Critical'
ELSE AI_COMPLETE('claude-haiku-4-5',
'Classify priority as Critical/High/Medium/Low. Return only the classification, nothing else.: ' || ticket_text)
END AS priority
FROM tickets;
That’s not a clever prompt. It’s a CASE statement on top of the AI call. But it’s the kind of thing that’s easy to forget – the model is so capable on the surface that practitioners stop thinking about the deterministic business rules they need to wrap around it.
The confusion matrix provides a crucial reality check: the model operates without inherent awareness of your specific customer tiers, revenue-critical product lines, or indicators of urgency, such as repeat support requests. That domain context is something only you can provide.
The general principle: “is the model good enough?” is almost never a yes/no question. The right question is “is the model good enough on the cases that matter, and are the business rules, that the model can’t infer on its own, encoded into the prompt?” You can’t answer either without the matrix.
The traditional ETL reflex is full reload – truncate, re-run, re-materialize every night. That’s fine when compute is cheap. With AI functions, it’s a budget event. A nightly full reload of a million-row table through AI_CLASSIFY re-bills the same inferences forever, even though 95% of the rows haven’t changed.
The rule is simple: process each row exactly once, on stable data, store the result, never recompute. Treat AI function output the way you’d treat the output of an expensive external API – because that’s effectively what it is.
A few patterns make this concrete.
Only process closed, immutable records. Don’t run AI on data still in flight. Open tickets, pending orders, draft documents – these will change, and every change means re-processing. Wait until they’re stable.
INSERT INTO ticket_ai_enriched
SELECT
ticket_id,
AI_CLASSIFY(ticket_text, ['bug','billing','feature','other']) AS category,
AI_SENTIMENT(ticket_text) AS sentiment
FROM raw_tickets r
WHERE status = 'closed'
AND closed_at < DATEADD('hour', -24, CURRENT_TIMESTAMP())
AND NOT EXISTS (
SELECT 1 FROM ticket_ai_enriched e WHERE e.ticket_id = r.ticket_id
);
The NOT EXISTS clause is the key. Each row is processed once, when it’s stable. The pipeline scales with new data, not total data.
Use streams and tasks for incremental processing. A pipeline running on a stream of new rows costs the same in year three as it does in week one. A pipeline doing nightly full reloads gets more expensive every day, forever.
Materialize, don’t recompute. Once you’ve paid for an inference, store it. Never put AI_COMPLETE inside a view that downstream dashboards query – every refresh re-bills the call. Materialize to a table, refresh on a schedule, query the table.
Separate AI enrichment from downstream transformation. Don’t mix AI calls into the same dbt model as the rest of your business logic. When the downstream logic changes – new column, renamed field, fixed CASE statement – the whole model rebuilds, which re-runs the AI calls. Split it:
raw_tickets
└─> ticket_ai_enriched (incremental, AI calls here, expensive)
└─> ticket_marts (full refresh OK, no AI calls, cheap)
Sample for exploration. When someone wants to try AI_SUMMARIZE on reviews, they run it on SAMPLE (1000 ROWS), not the full table. The cost difference between exploration on a sample and exploration on production is the difference between $0.05 and $500. Same insight either way.
Version your outputs. Keep a prompt_version or model_version column on enriched tables. When you change the prompt or switch models, you can re-process incrementally and know what came from where.
Snowflake gives you two ways to do many of the same jobs:
For routine, high-volume work where the average case is what matters, specialized functions are the right default. They’re cheaper than calling AI_COMPLETE with a premium model, easier to budget (flat rate, no model-selection variance), and produce more predictable output shapes that are easier to integrate downstream.
But specialized functions have a ceiling. They’re trained on the average case of a generic task. They don’t know your business.
AI_SENTIMENT will competently classify “this product is terrible” as negative. It will struggle with “finally, an invoice that’s only three weeks late this time” – sarcasm flipping the polarity. It doesn’t know that “we’ll be in touch” from a client in your industry almost always means the deal is dead.
AI_CLASSIFY handles broad categories well. It fails predictably on the cases that matter most: the ambiguous ones, the ones that span two categories, the ones where the right answer depends on context your data has but the function doesn’t.
This is where AI_COMPLETE earns its cost premium. Not because the model is “smarter” – but because the prompt lets you encode the things specialized functions don’t know:
-- Specialized: cheap, fast, no business context
AI_CLASSIFY(ticket_text,
['bug_report', 'feature_request', 'help_request',
'positive_review', 'complaint', 'account_billing']):labels[0]::STRING
-- Prompted: more expensive, knows what each category actually means
AI_COMPLETE('claude-sonnet-4-5',
'You are a support ticket classifier. Classify the following ticket into
exactly one of these categories:
1. bug_report - Something is broken, crashing, returning errors, or not
working as expected. The user is reporting a malfunction.
2. feature_request - The user is asking for new functionality, an
improvement, or a capability that does not exist yet. No current
issue, just a wish.
3. help_request - The user needs guidance on how to do something.
A how-to question, setup help, or configuration assistance. They
are not reporting a problem with the product itself.
4. positive_review - The user is expressing satisfaction, praise, or
a positive experience. No issue or request, just good feedback.
5. complaint - The user is frustrated or unhappy about service quality,
performance, pricing, or broken promises. They are venting
dissatisfaction, not reporting a specific technical bug.
6. account_billing - The user is asking about invoices, licenses,
pricing plans, payment methods, billing contacts, contracts,
upgrades, downgrades, or any financial/account administration topic.
If the ticket mentions money, invoices, subscriptions, user
licenses, or plan changes, it belongs here.
Return only the category name, nothing else.
Ticket: ' || ticket_text)
Both calls use the same six category labels. On the surface they look like they should produce the same result. They don’t.
AI_CLASSIFY sees the label strings and infers what they mean from the words themselves – bug_report is “something about bugs,” complaint is “something negative.” Fine for the obvious cases. But which bucket does a frustrated user reporting a broken feature go in – bug_report or complaint? Which bucket does a billing question wrapped in angry language go in – complaint or account_billing? The specialized function has no way to know your answer.
The prompted version defines each category in business terms. It tells the model that complaint is venting without a specific technical bug – so a frustrated bug report goes to bug_report, not complaint. It tells the model that anything mentioning invoices, subscriptions, or licenses belongs in account_billing regardless of tone – so an angry billing question doesn’t drift into complaint. Those boundary rules are invisible to AI_CLASSIFY. They’re the entire point of AI_COMPLETE.
Prompt engineering is the new business logic.
This prompt is a piece of business logic. Every sentence in it is a decision someone made about how the business wants tickets categorized. “If it mentions money, invoices, subscriptions, user licenses, or plan changes, it belongs here” – that’s a rule. “They are venting dissatisfaction, not reporting a specific technical bug” – that’s a tie-breaker for the ambiguous middle. Change one of those sentences and the downstream routing changes. Forget to encode one and tickets land in the wrong queue.
That means the prompt deserves the same treatment as a complex CASE statement in a dbt model: version controlled, code reviewed, documented, tested against the eval set before deployment. Store prompts in your dbt repo, not in ad-hoc SQL files. Treat changes to them as changes to business logic – because they are.
Don’t get blindsided by using AI – it won’t solve all your problems. Use as much deterministic logic as you can around it. A CASE statement, a customer-tier flag, a regex on the ticket subject, a lookup table of known product names – all of these are cheaper, faster, and more accurate than asking an LLM to figure them out. AI is the right tool for what only AI can do; everything else should stay in SQL.
When utilizing AI_COMPLETE, the choice of model is a strategic architectural decision rather than a stylistic one. Cost variances between models for identical tasks can be 30–60x. On a million-row workload, that’s the difference between $300 and $15,000 for identical output.
The default – reaching for the most capable model and calling it safe – does not apply here. The right default is the cheapest model that could plausibly do the job, measured against your eval set.
Where a small model is almost always enough:
Where a larger model starts to earn its price:
Best Practice: Execute each candidate model against the eval set once, store the predictions, and perform accuracy analysis from the cache. This approach follows the core principle governing production pipelines: pay for each inference exactly once. By caching predictions, you can slice accuracy analysis in multiple ways—such as by category, ticket length, or source—without re-billing a single token.
Furthermore, if you need to re-test after updating labels or adding eval rows, you only need to re-score the affected entries, avoiding redundant inference calls and minimizing costs.
-- Step 1: run each model once and cache predictions
INSERT INTO eval_predictions
SELECT
ticket_id,
'llama3.1-8b' AS model,
AI_COMPLETE('llama3.1-8b',
'Classify as bug/billing/feature/other. Return only the classification, nothing else.: ' || ticket_text) AS predicted_category,
CURRENT_TIMESTAMP() AS scored_at
FROM eval_set_tickets;
INSERT INTO eval_predictions
SELECT
ticket_id,
'claude-haiku-4-5' AS model,
AI_COMPLETE('claude-haiku-4-5',
'Classify as bug/billing/feature/other. Return only the classification, nothing else.: ' || ticket_text) AS predicted_category,
CURRENT_TIMESTAMP() AS scored_at
FROM eval_set_tickets;
-- Step 2: compute accuracy from the cache (cheap, repeatable, AI-free)
SELECT
p.model,
AVG(CASE WHEN p.predicted_category = e.true_category THEN 1 ELSE 0 END) AS accuracy
FROM eval_predictions p
JOIN eval_set_tickets e USING (ticket_id)
GROUP BY p.model;
If the cheap model hits your business threshold, ship it.
One more thing worth knowing: output tokens are typically billed at several times the rate of input tokens. Looking at Snowflake’s Service Consumption Table for the most-used models (credits per million tokens, as of May 2026):
| Model | Input | Output | Ratio |
| claude-sonnet-4-5 | 1.65 | 8.25 | 5.0x |
| openai-gpt-5 (long context) | 5.50 | 24.75 | 4.5x |
| snowflake-llama-3.3-70b | 0.29 | 0.29 | 1.0x |
The practical consequence: output length is a cost lever you control directly. Summarizing customer reviews on claude-sonnet-4-5, with a typical review running ~200 input tokens:
Same model, same input, 2.7x cost difference just from output length. Across a million reviews, that’s the difference between roughly 500 and 1,500 credits and the longer summary is rarely 2.7x more useful downstream.
Design prompts that produce only what you need.
-- Wasteful: open-ended output, no length constraint
AI_COMPLETE('claude-sonnet-4-5',
'Summarize this customer review.: ' || review_text)
-- Tight: specifies length, format, and what to extract
AI_COMPLETE('claude-sonnet-4-5',
'In max 20 words, summarize the main complaint
or praise in this review. Return only the sentence.
Review: ' || review_text)
Same model, same task. The second prompt produces shorter, more defined output, cutting the per-row cost significantly. At a million reviews that can be hundreds of credits saved – plus the one-sentence summary is usually more useful downstream than a rambling paragraph.
There’s no one right shape for an AI analytics pipeline – it depends on volume, latency requirements, cost tolerance, and how much business logic you need to encode. But a few design choices come up often enough that they’re worth considering for any production pipeline:
The shape will vary. The discipline is the same.
The promise of AI in SQL is real. Snowflake genuinely collapses the gap between “we have an idea” and “it’s running in production.” But the discipline that makes the difference between a demo and a system that delivers business value still looks like data science – eval sets, error inspection, cost-aware model choice, deterministic logic where it belongs. The tools made it easy to start. The craft is using them correctly.

Jan Šulc
Business Analyst at Revolt BI with hands-on experience in Snowflake and modern data platforms.
He designs scalable data models, automates data pipelines, and works on applying AI capabilities within enterprise analytics environments. Jan bridges business needs with technical architecture to help organizations operationalize data and AI.
SEE WHAT AI ANALYTICS COSTS ON YOUR ACTUAL DATA
Book a free 30-minute call. We’ll map your use case, pick the right model, and estimate costs — before you start building.