Home Database Cortex AI: ML, LLMs & AI Workloads in SQL
Advanced 3 min · July 17, 2026
Cortex AI: Machine Learning, LLMs, and AI Workloads

Cortex AI: ML, LLMs & AI Workloads in SQL

Learn to run machine learning, LLMs, and AI workloads directly in Snowflake using Cortex AI.

N
Naren Founder & Principal Engineer

20+ years shipping high-throughput database systems. Lessons pulled from things that broke in production.

Follow
Production
production tested
July 17, 2026
last updated
2,439
articles · all by Naren
Before you start⏱ 15-20 min read
  • Basic SQL knowledge
  • A Snowflake account with Cortex AI enabled
  • Appropriate role privileges (USAGE on SNOWFLAKE.CORTEX)
 ● Production Incident 🔎 Debug Guide ⚙ Triage Commands
Quick Answer
  • Run ML models and LLMs directly in Snowflake using SQL functions.
  • Use Cortex AI for sentiment analysis, translation, summarization, and anomaly detection.
  • No need to move data out of Snowflake for AI inference.
  • Supports custom models via Snowpark ML and external integrations.
  • Pay-per-query pricing with automatic scaling.
✦ Definition~90s read
What is Cortex AI?

Snowflake Cortex AI is a suite of AI capabilities that lets you run machine learning, LLMs, and custom AI workloads directly in Snowflake using SQL.

Imagine you have a huge library of books (your data) and you want to ask a smart assistant to summarize a book or find unusual stories.
Plain-English First

Imagine you have a huge library of books (your data) and you want to ask a smart assistant to summarize a book or find unusual stories. Normally, you'd have to copy the book and take it to a separate assistant. With Snowflake Cortex AI, the assistant lives inside the library. You just ask your question in SQL, and the assistant works on the books right there, without moving them.

In the modern data landscape, organizations are collecting vast amounts of data but often struggle to derive actionable insights quickly. Traditional analytics can tell you what happened, but AI workloads—like sentiment analysis, anomaly detection, and natural language processing—can tell you why and what to do next. However, moving data to specialized AI platforms introduces latency, cost, and security risks.

Snowflake Cortex AI changes this by bringing AI directly into your data warehouse. It provides a suite of SQL-based functions for machine learning inference, large language model (LLM) capabilities, and custom model deployment—all without leaving Snowflake. This means you can enrich your data with AI predictions in real-time, build intelligent applications, and automate decision-making using the same SQL you already know.

In this tutorial, you'll learn how to use Cortex AI for common tasks like sentiment analysis, translation, summarization, and anomaly detection. We'll cover production-ready examples, debugging techniques, and a real-world incident that highlights the importance of understanding model behavior. By the end, you'll be able to integrate AI into your data pipelines with confidence.

What is Snowflake Cortex AI?

Snowflake Cortex AI is a suite of AI capabilities built directly into Snowflake's data cloud. It allows you to perform machine learning inference, leverage large language models (LLMs), and run custom AI workloads using standard SQL. No need to export data or manage separate infrastructure.

Key components include
  • Cortex ML Functions: Pre-built ML models for tasks like anomaly detection, forecasting, and classification.
  • Cortex LLM Functions: Access to powerful LLMs (e.g., Snowflake Arctic, Llama) for text generation, summarization, translation, and sentiment analysis.
  • Snowpark ML: For training and deploying custom models using Python or Scala.
  • Cortex Search: Semantic search over your data using embeddings.

All of these are accessible via SQL functions like SNOWFLAKE.CORTEX.COMPLETE, SNOWFLAKE.CORTEX.SENTIMENT, SNOWFLAKE.CORTEX.ANOMALY_DETECTION, etc. The underlying infrastructure is fully managed, so you only pay for the queries you run.

cortex_overview.sqlSQL
1
2
3
4
5
6
7
8
-- Check available Cortex functions
SELECT function_name
FROM information_schema.functions
WHERE function_schema = 'CORTEX'
  AND function_catalog = 'SNOWFLAKE';

-- Example: Sentiment analysis
SELECT SNOWFLAKE.CORTEX.SENTIMENT('I love this product!') AS sentiment;
Output
+-----------+
| sentiment |
+-----------+
| positive |
+-----------+
🔥Prerequisites
📊 Production Insight
Always check the region availability; Cortex AI is not available in all Snowflake regions yet.
🎯 Key Takeaway
Cortex AI brings AI to your data, not the other way around. Start with pre-built functions for quick wins.

Setting Up Your Environment

Before using Cortex AI, ensure your Snowflake account has the feature enabled. You can verify by running a simple function. If you get an error, contact your Snowflake admin.

  1. Enable Cortex AI: Typically enabled by default in supported regions. Check with SELECT SYSTEM$ENABLE_CORTEX_AI(); (if needed).
  2. Grant privileges: Your role needs USAGE ON DATABASE SNOWFLAKE and USAGE ON SCHEMA SNOWFLAKE.CORTEX.
  3. Test connectivity: Run a simple sentiment analysis.

For custom models, you'll also need to set up a Snowpark environment (Python) and a stage for model artifacts.

setup.sqlSQL
1
2
3
4
5
6
-- Grant necessary privileges (as admin)
GRANT USAGE ON DATABASE SNOWFLAKE TO ROLE analyst_role;
GRANT USAGE ON SCHEMA SNOWFLAKE.CORTEX TO ROLE analyst_role;

-- Test connectivity
SELECT SNOWFLAKE.CORTEX.SENTIMENT('Hello world!') AS test;
Output
+--------+
| test |
+--------+
| neutral|
+--------+
💡Quick Test
🎯 Key Takeaway
Setup is minimal—just grant permissions and test. You're ready to use AI in minutes.

Using LLMs for Text Generation and Summarization

Cortex AI provides access to powerful LLMs via the COMPLETE function. You can generate text, summarize documents, answer questions, and more. The function takes a model name and a prompt.

Available models include
  • snowflake-arctic (default, high quality)
  • snowflake-arctic-lite (faster, cheaper)
  • llama3-70b (third-party)
  • mistral-large (third-party)

Example: Summarize customer reviews.

llm_summarize.sqlSQL
1
2
3
4
5
-- Summarize a long review
SELECT SNOWFLAKE.CORTEX.COMPLETE(
  'snowflake-arctic',
  'Summarize the following customer review in one sentence: "I bought this product last week and it broke after two days. The customer service was unhelpful and I had to wait a week for a refund. Very disappointed."'
) AS summary;
Output
+------------------------------------------------------------------+
| summary |
+------------------------------------------------------------------+
| The customer is disappointed because the product broke quickly |
| and customer service was slow and unhelpful. |
+------------------------------------------------------------------+
⚠ Token Limits
📊 Production Insight
For production, consider using snowflake-arctic-lite for high-volume, low-latency needs. Monitor costs by reviewing query history.
🎯 Key Takeaway
Use COMPLETE for any text generation task. Choose the model based on quality vs. cost trade-offs.

Sentiment Analysis and Translation

Cortex AI offers specialized functions for common NLP tasks
  • SENTIMENT: Returns 'positive', 'negative', or 'neutral'.
  • TRANSLATE: Translates text between languages.
  • DETECT_LANGUAGE: Identifies the language of a text.

These are built on top of LLMs but optimized for speed and cost. Example: Analyze customer feedback in multiple languages.

sentiment_translate.sqlSQL
1
2
3
4
5
6
7
8
9
10
-- Sentiment analysis on a table of reviews
SELECT review_id, review_text,
       SNOWFLAKE.CORTEX.SENTIMENT(review_text) AS sentiment
FROM customer_reviews;

-- Translate French reviews to English
SELECT review_id,
       SNOWFLAKE.CORTEX.TRANSLATE(review_text, 'fr', 'en') AS translated
FROM customer_reviews
WHERE SNOWFLAKE.CORTEX.DETECT_LANGUAGE(review_text) = 'fr';
Output
+-----------+--------------------------------+-----------+
| review_id | review_text | sentiment |
+-----------+--------------------------------+-----------+
| 1 | This is amazing! | positive |
| 2 | Not good at all. | negative |
+-----------+--------------------------------+-----------+
🔥Language Codes
📊 Production Insight
Combine sentiment with translation to analyze global feedback. Be aware that sentiment may not capture sarcasm or cultural nuances.
🎯 Key Takeaway
Specialized functions are cheaper and faster than generic LLM calls for these tasks.

Anomaly Detection and Forecasting

Cortex ML functions allow you to detect anomalies and forecast time-series data without writing Python. Use ANOMALY_DETECTION and FORECAST.

Example: Detect anomalies in daily sales.

anomaly_detection.sqlSQL
1
2
3
4
5
6
7
8
9
10
11
12
-- Create a view with daily sales
CREATE OR REPLACE VIEW daily_sales AS
SELECT date, SUM(amount) AS sales
FROM transactions
GROUP BY date;

-- Detect anomalies
SELECT date, sales,
       SNOWFLAKE.CORTEX.ANOMALY_DETECTION(
         OBJECT_CONSTRUCT('timestamp_col', 'date', 'target_col', 'sales', 'contamination', 0.05)
       ) OVER (ORDER BY date) AS is_anomaly
FROM daily_sales;
Output
+------------+-------+------------+
| date | sales | is_anomaly |
+------------+-------+------------+
| 2024-01-01 | 1000 | false |
| 2024-01-02 | 1200 | false |
| 2024-01-03 | 5000 | true |
+------------+-------+------------+
💡Parameters
📊 Production Insight
For time-series, ensure your data is sorted by timestamp. Use a rolling window for real-time detection.
🎯 Key Takeaway
Anomaly detection and forecasting are one-liners in SQL. Great for monitoring dashboards.

Custom Models with Snowpark ML

For advanced use cases, you can train and deploy custom ML models using Snowpark ML. This involves writing Python code, registering the model in Snowflake, and then calling it via SQL.

Steps: 1. Train a model using Snowpark ML (e.g., XGBoost). 2. Save the model to a stage. 3. Register the model using CREATE MODEL. 4. Use PREDICT function in SQL.

Example: Train a simple linear regression model.

custom_model.pyPYTHON
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
from snowflake.ml.modeling.linear_model import LinearRegression
from snowflake.ml.modeling.pipeline import Pipeline
from snowflake.snowpark import Session

# Create session
session = Session.builder.configs({...}).create()

# Load data
snowdf = session.table('training_data')

# Train model
pipeline = Pipeline([('lr', LinearRegression())])
pipeline.fit(snowdf, input_cols=['feature1', 'feature2'], label_cols=['target'])

# Save model to stage
pipeline.save('@model_stage/my_model')

# Register model in Snowflake
session.sql("CREATE MODEL my_model FROM REFERENCE @model_stage/my_model").collect()
🔥Snowpark ML
📊 Production Insight
Monitor model drift by comparing predictions over time. Retrain periodically with new data.
🎯 Key Takeaway
Custom models give you full flexibility. Use Snowpark ML for training and SQL for inference.

Best Practices and Cost Optimization

Cortex AI pricing is based on the number of tokens processed (for LLMs) or compute time (for ML functions). To optimize costs: - Use smaller models (snowflake-arctic-lite) for high-volume tasks. - Batch requests: Instead of calling a function row-by-row, use a single SQL query that processes multiple rows. - Cache results: If the same input appears often, store the result in a table. - Monitor usage with QUERY_HISTORY view.

Also, consider security: Cortex AI functions run within Snowflake's security perimeter, so data never leaves. However, be cautious with sensitive data when using third-party models (e.g., Llama).

cost_monitor.sqlSQL
1
2
3
4
5
6
-- View recent Cortex AI usage
SELECT query_text, credits_used, start_time
FROM snowflake.account_usage.query_history
WHERE query_text LIKE '%SNOWFLAKE.CORTEX.%'
ORDER BY start_time DESC
LIMIT 10;
Output
+------------------------------------------------+-------------+-------------------------------+
| query_text | credits_used| start_time |
+------------------------------------------------+-------------+-------------------------------+
| SELECT SNOWFLAKE.CORTEX.SENTIMENT(...) | 0.001 | 2024-03-15 10:30:00.000+00:00 |
+------------------------------------------------+-------------+-------------------------------+
⚠ Data Privacy
📊 Production Insight
Set up alerts on credit usage to avoid unexpected bills. Use resource monitors.
🎯 Key Takeaway
Optimize costs by choosing the right model and batching queries. Monitor usage regularly.
● Production incidentPOST-MORTEMseverity: high

The Sentiment Analysis That Missed Sarcasm

Symptom
Customer satisfaction scores were abnormally high, but support tickets increased.
Assumption
The developer assumed the default sentiment model would handle all cases, including sarcasm.
Root cause
The default model was not fine-tuned for sarcasm detection; it relied on keyword matching.
Fix
Switched to a more advanced model (e.g., 'snowflake-arctic') and added a confidence threshold filter to flag low-confidence predictions for manual review.
Key lesson
  • Always test AI models on a sample of your actual data before production.
  • Understand the limitations of pre-built models (e.g., sarcasm, context).
  • Implement confidence thresholds to catch uncertain predictions.
  • Monitor model performance over time and retrain if needed.
  • Have a fallback mechanism (e.g., manual review) for edge cases.
Production debug guideSymptom to Action5 entries
Symptom · 01
Model returns NULL or error for valid input
Fix
Check if the input exceeds token limits (e.g., 4096 tokens). Use TRIM or SUBSTRING to reduce length.
Symptom · 02
Sentiment analysis returns wrong polarity
Fix
Test with a small sample to see if the model handles sarcasm/negation. Consider using a different model or adding a confidence filter.
Symptom · 03
Translation output is garbled
Fix
Verify the source language code (e.g., 'en' vs 'eng'). Use language detection first if unsure.
Symptom · 04
Anomaly detection flags too many false positives
Fix
Adjust the anomaly sensitivity parameter (e.g., 'contamination' or 'threshold'). Use a rolling window for time-series data.
Symptom · 05
Query runs slowly on large datasets
Fix
Use a smaller model variant (e.g., 'snowflake-arctic-lite') or batch process data in chunks.
★ Quick Debug Cheat SheetCommon issues and immediate actions for Cortex AI.
NULL result
Immediate action
Check input length
Commands
SELECT LENGTH(input_column) FROM table;
SELECT SNOWFLAKE.CORTEX.COMPLETE('model', SUBSTRING(input,1,4000)) FROM table;
Fix now
Truncate input to 4000 characters.
Wrong sentiment+
Immediate action
Test with known examples
Commands
SELECT SNOWFLAKE.CORTEX.SENTIMENT('This is great!') AS positive, SNOWFLAKE.CORTEX.SENTIMENT('This is terrible.') AS negative;
SELECT SNOWFLAKE.CORTEX.SENTIMENT('Yeah, right.') AS sarcasm;
Fix now
Switch to a more robust model or add confidence filter.
Translation error+
Immediate action
Verify language code
Commands
SELECT SNOWFLAKE.CORTEX.TRANSLATE('Hello', 'en', 'fr');
SELECT SNOWFLAKE.CORTEX.DETECT_LANGUAGE('Bonjour');
Fix now
Use DETECT_LANGUAGE to auto-detect source.
FeaturePre-built FunctionsCustom Models (Snowpark ML)
Ease of useSQL only, no codingRequires Python/Scala
FlexibilityLimited to predefined tasksFull control over model
CostPay per token/queryPay for compute + storage
PerformanceOptimized for speedDepends on model complexity
Use caseQuick insightsAdvanced, unique requirements
⚙ Quick Reference
7 commands from this guide
FileCommand / CodePurpose
cortex_overview.sqlSELECT function_nameWhat is Snowflake Cortex AI?
setup.sqlGRANT USAGE ON DATABASE SNOWFLAKE TO ROLE analyst_role;Setting Up Your Environment
llm_summarize.sqlSELECT SNOWFLAKE.CORTEX.COMPLETE(Using LLMs for Text Generation and Summarization
sentiment_translate.sqlSELECT review_id, review_text,Sentiment Analysis and Translation
anomaly_detection.sqlCREATE OR REPLACE VIEW daily_sales ASAnomaly Detection and Forecasting
custom_model.pyfrom snowflake.ml.modeling.linear_model import LinearRegressionCustom Models with Snowpark ML
cost_monitor.sqlSELECT query_text, credits_used, start_timeBest Practices and Cost Optimization

Key takeaways

1
Snowflake Cortex AI enables AI workloads directly in SQL, eliminating data movement.
2
Start with pre-built functions for common tasks like sentiment, translation, and anomaly detection.
3
For custom needs, use Snowpark ML to train and deploy models, then call them via SQL.
4
Optimize costs by choosing the right model, batching queries, and monitoring usage.
5
Always test models on your data and implement confidence thresholds for production reliability.

Common mistakes to avoid

3 patterns
×

Using the default model for all tasks without testing.

×

Ignoring token limits and getting NULL results.

×

Calling Cortex functions row-by-row in a loop instead of using set-based SQL.

INTERVIEW PREP · PRACTICE MODE

Interview Questions on This Topic

Q01JUNIOR
How do you perform sentiment analysis on a table of customer reviews usi...
Q02SENIOR
Explain the difference between using `COMPLETE` and `SENTIMENT` for sent...
Q03SENIOR
How would you deploy a custom XGBoost model in Snowflake and use it for ...
Q01 of 03JUNIOR

How do you perform sentiment analysis on a table of customer reviews using Snowflake Cortex AI?

ANSWER
Use the SNOWFLAKE.CORTEX.SENTIMENT function in a SELECT query: SELECT review_id, SNOWFLAKE.CORTEX.SENTIMENT(review_text) AS sentiment FROM reviews;
FAQ · 5 QUESTIONS

Frequently Asked Questions

01
What models are available in Snowflake Cortex AI?
02
Can I use my own custom model with Cortex AI?
03
How is Cortex AI priced?
04
Is my data secure when using Cortex AI?
05
What are the token limits for LLM functions?
N
Naren Founder & Principal Engineer

20+ years shipping high-throughput database systems. Lessons pulled from things that broke in production.

Follow
Verified
production tested
July 17, 2026
last updated
2,439
articles · all by Naren
🔥

That's Snowflake. Mark it forged?

3 min read · try the examples if you haven't

Previous
Monitoring: Account Usage, Query History, and Observability
20 / 33 · Snowflake
Next
External Tables, Iceberg, and Multi-Cloud Data Access