Cortex AI: ML, LLMs & AI Workloads in SQL
Learn to run machine learning, LLMs, and AI workloads directly in Snowflake using Cortex AI.
20+ years shipping high-throughput database systems. Lessons pulled from things that broke in production.
- ✓Basic SQL knowledge
- ✓A Snowflake account with Cortex AI enabled
- ✓Appropriate role privileges (USAGE on SNOWFLAKE.CORTEX)
- 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.
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.
- 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.
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.
- Enable Cortex AI: Typically enabled by default in supported regions. Check with
SELECT SYSTEM$(if needed).ENABLE_CORTEX_AI(); - Grant privileges: Your role needs
USAGE ON DATABASE SNOWFLAKEandUSAGE ON SCHEMA SNOWFLAKE.CORTEX. - 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.
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.
snowflake-arctic(default, high quality)snowflake-arctic-lite(faster, cheaper)llama3-70b(third-party)mistral-large(third-party)
Example: Summarize customer reviews.
snowflake-arctic-lite for high-volume, low-latency needs. Monitor costs by reviewing query history.COMPLETE for any text generation task. Choose the model based on quality vs. cost trade-offs.Sentiment Analysis and Translation
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.
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.
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.
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).
The Sentiment Analysis That Missed Sarcasm
- 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.
SELECT LENGTH(input_column) FROM table;SELECT SNOWFLAKE.CORTEX.COMPLETE('model', SUBSTRING(input,1,4000)) FROM table;| File | Command / Code | Purpose |
|---|---|---|
| cortex_overview.sql | SELECT function_name | What is Snowflake Cortex AI? |
| setup.sql | GRANT USAGE ON DATABASE SNOWFLAKE TO ROLE analyst_role; | Setting Up Your Environment |
| llm_summarize.sql | SELECT SNOWFLAKE.CORTEX.COMPLETE( | Using LLMs for Text Generation and Summarization |
| sentiment_translate.sql | SELECT review_id, review_text, | Sentiment Analysis and Translation |
| anomaly_detection.sql | CREATE OR REPLACE VIEW daily_sales AS | Anomaly Detection and Forecasting |
| custom_model.py | from snowflake.ml.modeling.linear_model import LinearRegression | Custom Models with Snowpark ML |
| cost_monitor.sql | SELECT query_text, credits_used, start_time | Best Practices and Cost Optimization |
Key takeaways
Common mistakes to avoid
3 patternsUsing 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 Questions on This Topic
How do you perform sentiment analysis on a table of customer reviews using Snowflake Cortex AI?
SNOWFLAKE.CORTEX.SENTIMENT function in a SELECT query: SELECT review_id, SNOWFLAKE.CORTEX.SENTIMENT(review_text) AS sentiment FROM reviews;Frequently Asked Questions
20+ years shipping high-throughput database systems. Lessons pulled from things that broke in production.
That's Snowflake. Mark it forged?
3 min read · try the examples if you haven't