Sharpen your SQL skills for data engineering and analysis. Learn advanced techniques, query optimization, window functions, CTEs, and effective data modeling patterns.
I passed the SnowPro Gen AI certification not too long ago. Within the same week I was back at my desk staring at a broken pipeline that no multiple-choice question had ever prepared me for. The cert looked great on my profile. It fixed exactly nothing about the actual problem in front of me.
I’m not saying certifications are worthless. I’m saying the industry has developed a quietly dishonest relationship with them — one where vendors, hiring managers, and candidates all play along with a fiction that a passed exam means something it doesn’t. Nobody wants to be the one to say it out loud.
So I will. Let me be direct about what’s actually going on.
TL;DR
Certifications test what vendors want you to know about their products — not whether you can actually engineer data systems that work under real conditions
The exam content is often months or years behind the tools you’ll actually use in production
Hiring managers use certs as a filter because it’s easy — not because it’s accurate
You can pass most data engineering certs with two weeks of practice exams and zero production experience
The real signal employers should care about — and rarely do — is what you’ve built, what broke, and what you learned from it
Certifications have a specific, narrow value: they are a vocabulary test, not a competence test. Know what you’re paying for
WHAT CERTIFICATIONS ACTUALLY TEST
Let’s start with what’s literally on the exam. Take the Databricks Certified Data Engineer Associate . The exam covers Delta Lake concepts, basic Spark operations, Unity Catalog, Databricks workflows. Good things to know.
But the exam tests your ability to identify the correct answer from four options in a controlled environment. It does not test whether you can debug a production Spark job that’s been running for six hours and slowly consuming memory. It doesn’t test whether you can diagnose why a Delta merge is creating file fragmentation degrading query performance. It doesn’t test whether you can architect a pipeline that recovers gracefully when an upstream API starts returning malformed JSON at 3am.
Those are the problems data engineers actually face. None of them are in the certification.
A certification tells you that someone understood the conceptual framework of a product well enough to pass a vendor-designed exam. It tells you almost nothing about their ability to operate that product under adversarial conditions. And production is always adversarial.
Who designs these exams? The vendors. Who benefits when thousands of engineers study for, pay for, and pass these exams? The vendors. Certification programmes are not primarily educational products. They are marketing products that create a credentialled user base and deepen platform lock-in.
When Snowflake designs its certification exams ,the goal is not to produce engineers who can evaluate whether Snowflake is the right tool. The goal is to produce engineers deeply familiar with Snowflake’s architecture, syntax, and product positioning — engineers who will advocate for Snowflake when tooling decisions come up at their company.
The exam content is shaped by commercial interest, not by what data engineers actually need to know. The practical consequence: certifications optimise for breadth of product knowledge over depth of engineering judgment. You learn feature names, service limits, and recommended architectures. You don’t develop the instinct that tells you something is going to break before it breaks.
THE HIRING MANAGER TRAP
I’ve sat in hiring discussions where a candidate without certifications was dismissed faster than one with a string of logos after their name, despite the uncertified candidate having a demonstrably stronger GitHub portfolio and much more interesting answers about production incidents they’d owned.
Certifications persist in job postings because they’re easy to verify and hard to argue with. A cert is binary. Either you have it or you don’t. Technical judgment, architecture instinct, debugging ability — these require effort to assess.
⚠️ The signal problem: If you can pass a data engineering certification with two weeks of practice exams and no production experience — and you can — then having the certification tells an interviewer almost nothing about whether you can do the job. It tells them you can study for a test. That’s useful. But it’s not the same thing.
The engineers most dismissive of certifications are often the most experienced. The engineers who lean most heavily on cert lists are often the ones who haven’t done enough production work to know what the gap actually looks like.
THE STALE CONTENT PROBLEM
Data engineering moves fast. The tooling landscape in 2024 looks materially different from 2021. dbt Core has changed substantially. Apache Iceberg has gone from niche to mainstream. Lakehouse architecture has shifted from concept to default.
Certification exams do not move at this speed. Exam content is updated infrequently — sometimes annually, sometimes less. You can hold an AWS Data Engineer cert that emphasises EMR and Glue in patterns most teams have replaced with more modern tooling. You can hold a Databricks cert that doesn’t reflect how Unity Catalog has fundamentally changed governance.
The cert is not wrong. It’s just dated. And dated knowledge in data engineering isn’t neutral — it can actively mislead you about how things should be built.
I wrote about a related version of this in “Why I Stopped Using Snowflake Tasks for Orchestration” — official documentation and certification content often lags behind what practitioners have already learned through trial and error in production.
WHAT YOU ACTUALLY LEARN WHEN YOU STUDY FOR A CERT
Here’s the part I want to be fair about. Studying for a data engineering certification isn’t worthless. It’s just worth something different from what most people think.
When you study for the Google Professional Data Engineer exam, you learn the GCP data ecosystem — BigQuery, Dataflow, Pub/Sub, Cloud Composer, Dataproc — in a structured way. You develop a vocabulary. You understand how services relate to each other.
What it doesn’t give you is judgment. Judgment about when to use Dataflow versus Dataproc. When BigQuery’s cost model makes it the wrong tool despite its performance. When a simple Cloud Function is a better answer than a fully orchestrated pipeline.
The honest framing: a certification is a vocabulary test with a structured curriculum. If you’ve never worked on a platform and need to get up to speed quickly, studying for the cert is efficient. If you already have production experience, the cert adds limited signal beyond what’s already on your resume.
THE PRACTICE EXAM LOOPHOLE NOBODY WANTS TO DISCUSS
Most data engineering certifications can be passed with aggressive practice exam grinding and minimal practical experience. Platforms like Udemy , Whizlabs and ExamTopics sell practice exam bundles close enough to real questions that a disciplined studier can reverse-engineer most of the exam in two to three weeks.
I’ve seen candidates with zero Snowflake production experience pass the SnowPro Core exam in a week of evening study. I’ve seen engineers memorise their way through the AWS Data Engineer Associate without writing a single Glue job. The credential is indistinguishable from someone who earned it through genuine depth.
The vendors know this. They update exam content periodically to counter braindump culture, but it’s an arms race they’re perpetually losing.
WHAT ACTUALLY SIGNALS ENGINEERING COMPETENCE
If I’m hiring a data engineer, here’s what I actually want to see.
Tell me about a pipeline that broke in production. Not a hypothetical. What broke, how you found out, what the root cause was, how you fixed it, what you changed to prevent recurrence. This conversation reveals more engineering judgment than any certification.
Show me something you built. A GitHub repo .A dbt project. A pipeline architecture diagram with a written explanation. The work I’ve been documenting — from the problem with dbt incremental models to Snowflake zero-copy cloning gotchas — is far more useful signal than any certification I hold.
Tell me about a technical decision you disagreed with. Engineering judgment includes knowing when to push back, when to compromise, how to argue for a position with evidence. No cert tests this.
Walk me through how you’d approach this problem. Give them a real scenario — a data quality issue, a cost spike, a schema migration in a live system. Watch how they think, not just what they know.
The gap between what certifications measure and what engineering competence looks like is large enough that I’d rather see zero certifications with a detailed post-mortem of a real incident than four certs with nothing to show for the work.
WHEN CERTIFICATIONS ARE ACTUALLY WORTH PURSUING
You’re breaking into the field. If you’re transitioning into data engineering, certifications serve a genuine purpose. They give you structured curriculum and a credential that signals seriousness to employers who don’t yet have anything else to evaluate you on.
Your employer requires it. Many enterprise organisations and consulting firms have vendor partnership requirements mandating certified staff levels. In that case, the cert has real organisational value regardless of signal quality.
You’re learning a new platform systematically. Using cert study as structured onboarding to a new tool is legitimate. The curriculum forces breadth coverage self-directed learning often misses. Just know that completing the cert doesn’t mean you know how to use the platform well.
You’re in a market where it’s table stakes. In some geographies and sectors, certain certs are required to get an interview. Clear the gate, then demonstrate real depth in the room.
The certification isn’t the problem. The mythology around it is. The idea that passing the exam means you can build reliable data systems — that’s the fiction that causes real damage.
WHAT THE INDUSTRY SHOULD DO INSTEAD
Portfolio-based evaluation. A documented data engineering project — architecture decisions, tradeoffs, failures encountered — tells a hiring team far more than an exam score. GitHub already supports this.
Incident post-mortems as credentials. A well-written post-mortem demonstrates debugging methodology, systems thinking, and the ability to learn from failure. No certification tests these.
Practical assessments over multiple choice. The Databricks Data Engineer Professional is harder than most — it has a coding component requiring actual proficiency. More exams should work this way.
Open curriculum from neutral sources. The Data Engineering Handbook and open-source community resources are doing more for actual engineering capability than most vendor certification programmes.
FREQUENTLY ASKED QUESTIONS
Are data engineering certifications worth it in 2024? It depends on where you are in your career. For someone entering the field, certs provide structured curriculum and a credential that signals seriousness. For experienced engineers, your production track record carries far more weight with strong technical hiring teams. Certs are worth what they cost if you understand what they are: a vocabulary test, not a competence test.
Which data engineering certification is the most respected? Among practitioners, the Databricks Data Engineer Professional is generally seen as harder and more meaningful because it includes a practical component. Google Professional Data Engineer has strong enterprise name recognition. AWS Certified Data Engineer Associate is widely recognised in cloud-native teams. But respected by whom matters — strong engineering teams care less about cert logos than about demonstrated ability.
Can you become a data engineer without certifications? Absolutely. Many strong data engineers have no certifications at all. A track record of real work — systems built, incidents resolved, architectural decisions owned — is equally or more compelling to technical hiring teams worth impressing.
How long does it take to pass data engineering certification exams? Most candidates report 2–6 weeks of focused study. With aggressive practice exam preparation, some pass in under two weeks — which is part of what makes the credentials less meaningful than they appear.
Do data engineering certifications expire? Yes. AWS certifications expire after three years, Google Cloud after two, Databricks varies by level. Recertification tends to be easier than initial certification and often doesn’t reflect how dramatically the tooling has evolved.
What should a data engineering portfolio include instead of certifications? End-to-end pipeline projects with documented architecture decisions. Written post-mortems of production incidents. Data quality testing approaches. dbt projects with meaningful transformation logic. Cost analyses or performance optimisations from real environments. Anything that shows how you think, not just what tools you’ve touched.
This post is for data engineers and analytics leads whose Snowflake bill is driven by lots of short queries rather than heavy batch jobs. It explains why Snowflake’s 60-second minimum makes those queries expensive, shows two ways to get Snowflake data into DuckDB (Iceberg tables on S3, and ADBC for native tables), and gives a simple way to decide which workloads belong on which engine.
I’ve been building on Snowflake long enough to know the ritual. Warehouse wakes up. Query runs in three seconds. Warehouse idles. You get billed for sixty seconds anyway. Multiply that by every analyst, every BI dashboard refresh and every dbt run in your dev environment, and you end up with a bill that feels disconnected from the work that actually happened.
For a long time I assumed this was just the price of using a best-in-class cloud warehouse. What I didn’t realise until I started taking DuckDB seriously is that a meaningful part of that bill doesn’t have to exist at all.
The real problem: you pay for compute you didn’t use
Snowflake bills compute per second, but only after a 60-second minimum each time a warehouse resumes from suspension. A query that takes five seconds gets billed for a full minute. You paid for 55 seconds of nothing.
It gets worse at scale. When a BI dashboard fires 20 queries on load, each taking three seconds, that single page view triggers 1,200 seconds of billed compute time. The actual work is one minute.
Warehouse sizing compounds it further. Each size increase in Snowflake doubles credit consumption, so teams defaulting to Medium or Large for everything pay a 4x to 8x premium for workloads that would run fine on X-Small.
I’ve seen this exact pattern on almost every Snowflake environment I’ve worked in: oversized warehouse, auto-suspend set to ten minutes, no resource monitors, and nobody looking at query history.
Quick wins inside Snowflake first
Before touching the architecture, fix the obvious things. These alone can cut spend by 20 to 40%.
Set AUTO_SUSPEND to exactly 60 seconds. Not lower: setting it below 60 is counterproductive, because a query arriving in that first minute triggers another 60-second minimum. Not higher: every idle second past 60 is wasted money.
Default to X-Small warehouses. Only scale up when a specific workload has a documented SLA that needs it.
Add resource monitors:
CREATE OR REPLACE RESOURCE MONITOR monthly_etl_monitor
WITH CREDIT_QUOTA = 5000
TRIGGERS ON 75 PERCENT DO NOTIFY
ON 100 PERCENT DO SUSPEND;
ALTER WAREHOUSE etl_heavy_wh
SET RESOURCE_MONITOR = monthly_etl_monitor;
This notifies at 75% of a 5,000-credit quota and suspends the warehouse at 100%. Set the quota and the warehouse name to match your own account.
Method 1: Query Snowflake Iceberg tables directly in DuckDB
If your organisation has moved to Iceberg tables with the underlying data in S3, you can read those tables directly in DuckDB. No Snowflake warehouse runs and no credits are consumed.
SELECT
customer_id,
COUNT(*)
FROM iceberg_scan('s3://your-bucket/path/to/metadata/00001-xxxx.metadata.json')
GROUP BY 1;
Materialise once for fast repeated queries
CREATE TABLE payments AS
SELECT * FROM iceberg_scan('s3://your-bucket/.../metadata.json');
After this, the same aggregation runs in 1.5 seconds instead of 54.
One benchmark: a SELECT * on a 110-million-row table finished in 29 seconds in DuckDB on an M1 MacBook. The same query on an X-Small Snowflake warehouse took 72 seconds.
The limitation
DuckDB’s Iceberg support is still maturing. You need direct S3 access, and you have to point DuckDB at a specific metadata file rather than a catalog. This will improve over time, but it works today.
Method 2: Query native Snowflake tables through ADBC
Not on Iceberg yet? ADBC (Arrow Database Connectivity) is the right tool here.
Why ADBC rather than ODBC
Apache Arrow is a columnar memory format. When you connect Snowflake to DuckDB through ADBC, data stays columnar the whole way. Traditional ODBC makes Snowflake convert columnar data to rows for transfer, and then DuckDB converts the rows back to columnar for processing. DuckDB’s benchmarks show ADBC is up to 38x faster than ODBC.
Connect to Snowflake and pull data as an Arrow table:
import adbc_driver_snowflake.dbapi
import duckdb
import os
from read_private_key import read_private_key
SNOWFLAKE_CONFIG = {
'adbc.snowflake.sql.account': os.getenv('SNOWFLAKE_ACCOUNT'),
'adbc.snowflake.sql.warehouse': os.getenv('SNOWFLAKE_WAREHOUSE'),
'adbc.snowflake.sql.role': os.getenv('SNOWFLAKE_ROLE'),
'adbc.snowflake.sql.database': os.getenv('SNOWFLAKE_DATABASE'),
'username': os.getenv('SNOWFLAKE_USER'),
'adbc.snowflake.sql.client_option.jwt_private_key_pkcs8_value': pem_key,
'adbc.snowflake.sql.auth_type': 'auth_jwt'
}
snowflake_conn = adbc_driver_snowflake.dbapi.connect(
db_kwargs={**SNOWFLAKE_CONFIG}
)
snowflake_cursor = snowflake_conn.cursor()
snowflake_cursor.execute("SELECT * FROM SANDBOX_DB.MY_SCHEMA.RAW_ORDERS")
# Fetch as Arrow table — stays columnar, no serialisation overhead
arrow_table = snowflake_cursor.fetch_arrow_table()
# Persist locally in DuckDB
duckdb_conn = duckdb.connect('demo.db')
duckdb_conn.execute("""
CREATE TABLE IF NOT EXISTS raw_orders AS
SELECT * FROM arrow_table
""")
The script reads the account, warehouse, role, database and user from environment variables, authenticates with a key pair (JWT), runs one query through a Snowflake warehouse, fetches the result as an Arrow table and writes it into a local DuckDB file called demo.db. Swap in your own table name and file path. pem_key has to be set before the config dictionary is built, using the read_private_key helper in the next section.
Encode the private key as PEM
One heads-up: working out the connection parameters for a private key is not straightforward, and the docs aren’t great on this point. The private key needs to be re-encoded into PEM format before you pass it to the ADBC driver:
from cryptography.hazmat.primitives import serialization
def read_private_key(private_key_path: str, private_key_passphrase: str = None) -> str:
with open(private_key_path, 'rb') as key_file:
private_key = serialization.load_pem_private_key(
key_file.read(),
password=private_key_passphrase.encode() if private_key_passphrase else None
)
pem_key = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption()
)
return pem_key.decode('utf-8')
The function loads your key file (using the passphrase if there is one) and returns it as an unencrypted PKCS8 PEM string, which is the format the jwt_private_key_pkcs8_value option expects.
Once that’s sorted, the workflow is clean: pull data from Snowflake through ADBC once, materialise it locally in DuckDB, and query it as many times as you want. No Snowflake credits are consumed after the initial pull.
Method 3: Route workloads by type
The two methods above are great for development and ad-hoc analysis. For production BI workloads, the cleanest solution I’ve seen is a hybrid architecture where you triage queries by workload type.
What made this click for me was using Snowflake’s query_history to categorise what is actually running:
WITH query_stats AS (
SELECT
warehouse_name,
user_name,
query_id,
execution_time / 1000 AS execution_seconds
FROM snowflake.account_usage.query_history
WHERE
start_time >= DATEADD('day', -30, CURRENT_TIMESTAMP())
AND warehouse_name IS NOT NULL
AND execution_status = 'SUCCESS'
)
SELECT
warehouse_name,
user_name,
COUNT(query_id) AS query_count,
MEDIAN(execution_seconds) AS median_execution_seconds,
CASE
WHEN query_count > 1000 AND median_execution_seconds < 30
THEN 'Interactive BI / High Frequency'
WHEN query_count <= 1000 AND median_execution_seconds < 60
THEN 'Ad-Hoc Exploration'
WHEN median_execution_seconds >= 300
THEN 'Batch ETL / Heavy Analytics'
ELSE 'General Purpose'
END AS workload_category
FROM query_stats
GROUP BY warehouse_name, user_name
ORDER BY query_count DESC;
The query looks at the last 30 days of successful queries, groups them by warehouse and user, and labels each group by how often it runs and how long its typical query takes. The thresholds (1,000 queries, 30, 60 and 300 seconds) are the cut-offs to adjust for your own account.
Use MEDIAN, not AVG. Outlier queries skew the average and give a misleading picture of typical duration.
Routing logic
Short, bursty BI (under 30 seconds, high frequency): move to a usage-based engine such as MotherDuck. The math: $528/month on a Snowflake X-Small running continuously vs $5.87/month on per-second billing for the same workload.
Dev and CI/CD: local DuckDB, zero cloud credits.
Heavy batch ETL, multi-TB: keep on Snowflake. The 60-second minimum is irrelevant for hour-long jobs.
This is the same principle I apply to orchestration: use the right tool for the job, not the most powerful tool for everything. I wrote about a similar decision in why I stopped using Snowflake Tasks for orchestration. The short version is that mature orchestration tools give you far more control over exactly this kind of workload routing.
When to stay on Snowflake
Multi-terabyte batch processing. Predictable provisioned compute matters more than idle cost savings when a job runs for hours.
Enterprise governance. Complex data masking, RBAC at scale and data residency requirements. Snowflake’s security surface is mature; DuckDB isn’t designed for this.
Already-efficient workloads. If a warehouse runs at high utilisation for eight hours straight, there’s no idle tax to remove. Don’t fix what isn’t broken.
What real cost savings look like
One SaaS company: 70%+ reduction in warehousing costs after moving to a DuckDB-based solution.
Okta: $60,000/month of Snowflake spend for threat detection reduced substantially using parallel DuckDB instances.
A data engineering team: 79% immediate reduction in Snowflake BI spend using DuckDB as a caching layer, with 7x faster queries.
None of these required abandoning Snowflake. They required deciding which workloads actually needed it. If you’re earlier in that journey, the rest of the data engineering articles on this site cover the Snowflake side in more depth.
Frequently asked questions
Can you query Snowflake data in DuckDB without a Snowflake warehouse running?
Yes, in two ways: Iceberg tables through the iceberg extension (no warehouse), or native tables through ADBC. ADBC needs a brief initial connection, but once the data is materialised locally, every later query is free.
What is ADBC and why is it faster than ODBC?
ADBC keeps data in columnar format throughout. ODBC forces a columnar to row to columnar conversion. DuckDB’s benchmarks show ADBC up to 38x faster for transfers.
How much can I realistically save?
For short, high-frequency dashboard queries, 70 to 90% is consistent across documented cases. The 60-second minimum means a 4-second query costs 15x what it should.
Is DuckDB production-ready?
For single-node analytical workloads under a few terabytes, yes. For multi-user concurrency at scale and enterprise governance, not yet.
Do I need Iceberg?
No. ADBC works with native Snowflake tables. The main friction is private key encoding, which the docs don’t explain well.
Will this work with dbt?
Yes. dbt-duckdb lets you run your full dbt project locally against DuckDB. Pull source data from Snowflake once, develop and test for free, and deploy to Snowflake only in production. That removes cloud compute costs from the whole development loop. I’ve written about dbt native projects and pipeline patterns if you want more context on how this fits into a Snowflake-first stack.
It was a Tuesday morning when I finally snapped. My dbt project had grown to 147 models, and the daily run was taking 2 hours and 47 minutes. Our Airflow DAG was timing out. The business team was complaining about stale dashboards. And I was spending my entire morning investigating why dim_customer alone was taking 45 minutes to build.
I had tried everything: manual query optimization, clustering keys, switching materializations. Each fix helped a little, but I was basically guessing. Then someone on the data engineering Slack mentioned using Snowflake Cortex Code to analyze their dbt manifest file.
“Wait, it can do WHAT?” I asked.
That question changed my entire workflow. Three months later, my dbt runs average 1 hour 23 minutes—a 48% improvement. I spend 90% less time debugging performance. And I actually have time to build new features instead of firefighting slow models.
This isn’t a tutorial about how Cortex Code might help you. This is the real story of how it actually transformed my day-to-day work as a data engineer, with specific examples, exact prompts I use, and honest numbers about what works and what doesn’t.
Before I get into the dbt deep dive, let me explain what Cortex Code actually is—because the marketing doesn’t do it justice.
Cortex Code is code generation AI built directly into Snowflake. Think ChatGPT, but it:
Understands your Snowflake schema automatically
Knows dbt best practices
Can analyze JSON files (like manifest.json)
Generates production-ready SQL, Python, and more
Lives where you already work (Snowflake UI, or via API)
How it’s different from GitHub Copilot or ChatGPT:
Feature
Cortex Code
GitHub Copilot
ChatGPT
Knows your Snowflake schema
✅ Yes
❌ No
❌ No
Can read manifest.json
✅ Yes
❌ No
⚠️ Manual paste
Snowflake-specific SQL
✅ Optimized
⚠️ Generic
⚠️ Generic
dbt best practices
✅ Built-in
⚠️ Learns from code
⚠️ General knowledge
Privacy/Security
✅ Snowflake environment
⚠️ Code leaves editor
❌ Data uploaded
The key difference for data engineers: Cortex Code actually understands your data warehouse context.
Part 2: Getting Started (5-Minute Setup)
Step 1: Enable Cortex Code
Cortex Code is available in Snowflake (check your edition—Enterprise or higher typically has it).
Step 1: Enable Cortex Code
Cortex Code is available in Snowflake (check your edition—Enterprise or higher typically has it).
-- Check if you have access
SELECT SYSTEM$GET_CORTEX_FEATURES();
-- If available, you're good to go
-- No additional setup needed
Step 2: First Test
How to Access Cortex Code:
Open Snowsight (Snowflake UI)
Look for the “AI Assistant” or “Cortex Code” button (usually in the sidebar or bottom-right)
Type your prompt in natural language
Get generated code instantly
Example first prompt:
Generate SQL to find top 10 customers by revenue from my customers and orders tables
Cortex Code responds with:
SELECT
c.customer_id,
c.customer_name,
SUM(o.order_amount) as total_revenue
FROM customers c
JOIN orders o ON c.customer_id = o.customer_id
GROUP BY c.customer_id, c.customer_name
ORDER BY total_revenue DESC
LIMIT 10;
That’s it. No installation, no API keys, no configuration. Just natural language prompts.
My first “wow” moment: I typed “generate a complete dbt model for customer lifetime value with staging, intermediate, and mart layers” and it produced three properly structured models with naming conventions, tests, and documentation. Took 30 seconds.
Part 3: Core Capabilities (The Quick Tour)
Before we dive deep into dbt, here’s what Cortex Code can do:
Before SQL Generation:
Complex queries with CTEs, window functions, aggregations
Query optimization suggestions
Data quality checks
dbt Development:
Model generation (staging, marts, facts, dimensions)
Yes, Cortex Code can generate dbt models. Ask it for a staging model, it’ll give you:
-- Example prompt: "Generate dbt staging model for raw_customers"
-- models/staging/stg_customers.sql
with source as (
select * from {{ source('raw', 'customers') }}
),
renamed as (
select
customer_id,
customer_name,
email,
created_at,
updated_at
from source
)
select * from renamed
But honestly? That’s the boring stuff. Any code generation tool can do this. Where Cortex Code becomes indispensable is performance optimization using your actual dbt metadata.
4.2: Performance Optimization – The Killer Feature
This is where I went from “this is neat” to “I can’t work without this anymore.”
Daily Airflow timeout failures: 2-3 times per week
Time spent debugging performance: 6-8 hours per week
I had no systematic way to know:
Which models were actually slow?
Why were they slow?
What should I optimize first?
Were my optimizations working?
I was flying blind, making educated guesses based on gut feeling and manual timing of individual models.ed on gut feeling and manual timing of individual models.
A) Manifest.json Analysis – The Secret Weapon
Your dbt project generates a manifest.json file in the target/ folder after every run. It contains:
Every model’s metadata
Dependencies between models
Column information
Schema details
I never really looked at it. It’s thousands of lines of JSON. Until Cortex Code.
How to use it:
Step 1: Upload manifest.json to Snowflake
-- Create a stage for your dbt metadata
CREATE STAGE IF NOT EXISTS dbt_metadata;
-- Upload the file (via SnowSQL or Snowsight UI)
PUT file://~/dbt_project/target/manifest.json @dbt_metadata/;
Step 2: Open Cortex Code interface in Snowsight
Click on the “AI Assistant” or “Cortex Code” button in Snowsight
This opens the natural language interface
Step 3: Ask Cortex Code to analyze it
Type this prompt in the Cortex Code interface:
Analyze the manifest.json file in my dbt_metadata stage and identify the top 10 slowest models with specific optimization recommendations.
Focus on:
- Materialization strategies (table vs incremental)
- Clustering opportunities
- Complex CTEs that could be simplified
- Join patterns that could be optimized
Provide specific code changes and estimated time savings for each recommendation.
Step 4: Review the analysis
Cortex Code responds with detailed analysis (example of what I got):
Top 10 Slowest Models Analysis:
1. dim_customer (45.2 minutes)
Issues identified:
- Full table scan on 50M+ rows daily
- No clustering key on frequently filtered columns
- Using table materialization when incremental would work
- 3 CTEs doing similar aggregations (could be deduplicated)
Recommendations:
- Add clustering key on (customer_id, updated_date)
- Convert to incremental materialization
- Use dbt_utils.deduplicate macro
- Estimated improvement: 35-40 minutes
2. fact_orders_daily (23.7 minutes)
Issues identified:
- Window functions not optimized
- Joining to dim_customer before aggregation
- Missing partition by date
Recommendations:
- Aggregate first, then join
- Add partition_by clause to window functions
- Consider separate monthly partitions
- Estimated improvement: 15-18 minutes
3. mart_customer_360 (18.4 minutes)
...
I was stunned. This analysis would have taken me days to do manually—if I even knew where to start. Cortex Code did it in 30 seconds.
B) Implementing the Recommendations
Let me show you exactly what I did for dim_customer:
Before (45 minutes):
-- models/marts/dim_customer.sql
{{
config(
materialized='table'
)
}}
with customers as (
select * from {{ ref('stg_customers') }}
),
orders as (
select * from {{ ref('fct_orders') }}
),
aggregated as (
select
c.customer_id,
c.customer_name,
c.email,
c.created_at,
count(o.order_id) as total_orders,
sum(o.order_amount) as lifetime_value,
max(o.order_date) as last_order_date
from customers c
left join orders o on c.customer_id = o.customer_id
group by 1,2,3,4
)
select * from aggregated
After (8 minutes) following Cortex Code suggestions:
-- models/marts/dim_customer.sql
{{
config(
materialized='incremental',
unique_key='customer_id',
cluster_by=['customer_id', 'updated_date'],
on_schema_change='append_new_columns'
)
}}
with customers as (
select * from {{ ref('stg_customers') }}
{% if is_incremental() %}
where updated_date >= (select max(updated_date) from {{ this }})
{% endif %}
),
orders_aggregated as (
-- Aggregate BEFORE joining (Cortex suggestion!)
select
customer_id,
count(order_id) as total_orders,
sum(order_amount) as lifetime_value,
max(order_date) as last_order_date
from {{ ref('fct_orders') }}
{% if is_incremental() %}
where order_date >= (select max(last_order_date) from {{ this }})
{% endif %}
group by customer_id
),
final as (
select
c.customer_id,
c.customer_name,
c.email,
c.created_at,
c.updated_date,
coalesce(o.total_orders, 0) as total_orders,
coalesce(o.lifetime_value, 0) as lifetime_value,
o.last_order_date
from customers c
left join orders_aggregated o on c.customer_id = o.customer_id
)
select * from final
Changes made:
✅ Switched to incremental materialization
✅ Added clustering keys on customer_id and updated_date
✅ Aggregated orders before joining (huge win!)
✅ Added incremental logic to only process new/changed data
The run_results.json file contains actual execution times and metadata from your last dbt run. Even more valuable than manifest for performance debugging.
My weekly performance review process:
-- Upload run_results from this week and last week
PUT file://~/dbt_project/target/run_results.json @my_stage/current/;
PUT file://~/dbt_project_backup/target/run_results.json @my_stage/previous/;
Example output:
Performance Regression Analysis:
CRITICAL REGRESSIONS (>50% slower):
1. mart_sales_summary
- Previous: 4.2 min
- Current: 9.8 min (+133%)
- Root cause: Source table fct_sales grew from 10M to 25M rows
- Recommendation: Add incremental logic with date partitioning
2. dim_product
- Previous: 2.1 min
- Current: 5.4 min (+157%)
- Root cause: New join to external API table (no clustering)
- Recommendation: Materialize API data first, add clustering key
MODERATE REGRESSIONS (20-50% slower):
3. stg_orders
- Previous: 1.2 min
- Current: 1.6 min (+33%)
- Root cause: New data quality test added (full table scan)
- Recommendation: Convert test to incremental or sampling
IMPROVEMENTS:
1. dim_customer: 45 min → 8 min (-82%) ✅ [Your optimization worked!]
2. fact_orders_daily: 23 min → 12 min (-48%) ✅
NEW BOTTLENECKS:
- mart_customer_cohort now takes 14 min (wasn't slow before)
- Likely due to dim_customer changes propagating downstream
- Recommendation: Review joins, consider pre-aggregation
This is gold. I immediately know what broke, why, and how to fix it.
D) Automated Performance Audits
I set up a weekly routine every Monday morning using Cortex Code:
My Monday Morning Workflow:
Run my standardized audit prompt
Upload latest manifest and run_results (automated via simple Python script)
Open Cortex Code interface
Perform a comprehensive dbt performance audit using the manifest.json and run_results.json in my dbt_metadata stage:
Analysis needed:
1. Identify slowest 15 models with root cause analysis
2. Detect performance anti-patterns:
- Models using full refresh that should be incremental
- Missing clustering keys on large tables
- Inefficient join patterns
- Unnecessary full table scans
3. Find models that should be incremental but aren't
4. Suggest clustering keys based on filter/join patterns in SQL
5. Recommend materialization strategies (table vs view vs incremental)
6. Calculate estimated monthly compute time savings for each recommendation
7. Rank by effort/impact ratio (quick wins vs long-term projects)
Format as prioritized action plan with:
- Quick wins (high impact, <1 hour effort)
- Medium effort items (2-4 hours)
- Strategic improvements (>4 hours)
- Estimated ROI for each
Sample output from last Monday:
dbt Performance Audit - 2026-01-20
QUICK WINS (High Impact, Low Effort):
1. Add clustering to dim_geography on (country_code, region_id)
- Current: 6.2 min | Estimated after: 1.5 min | Effort: 5 min
- Impact: Save 4.7 min per run = 33 hours/month
2. Convert fct_user_sessions to incremental
- Current: 11.3 min | Estimated after: 2.1 min | Effort: 20 min
- Impact: Save 9.2 min per run = 65 hours/month
MEDIUM EFFORT, HIGH IMPACT:
3. Refactor mart_product_performance (split into 2 models)
- Current: 18.7 min | Estimated after: 7 min + 4 min | Effort: 2 hours
- Impact: Save 7.7 min per run = 54 hours/month
ANTI-PATTERNS DETECTED:
⚠️ 8 models using table materialization with full refresh daily (should be incremental)
⚠️ 4 models missing clustering keys despite large table scans
⚠️ 2 models with circular dependency risk
TOTAL ESTIMATED MONTHLY SAVINGS: 247 hours of compute time
TOTAL IMPLEMENTATION EFFORT: ~8 hours
ROI: 30:1
I tackle 2-3 items from this list each week. In three months, I’ve saved 48% of total dbt runtime.
4.3: Real Production Examples
Let me share three actual scenarios where Cortex Code saved my ass:
Example 1: The Mysterious Slowdown
Problem:mart_revenue_daily suddenly went from 5 minutes to 32 minutes. No code changes, just suddenly slow.
What I did:
Analyze this slow dbt model. It suddenly went from 5 minutes to 32 minutes with no code changes.
Context:
- Model name: mart_revenue_daily
- Previous runtime: 5 min
- Current runtime: 32 min
- No changes to model SQL in past month
- Fact table grew from 50M to 180M rows last week
Here's the compiled SQL from dbt:
[I pasted the full compiled SQL here]
Please:
1. Identify the root cause of slowdown
2. Point to specific problematic lines in the SQL
3. Provide concrete fix with rewritten SQL
4. Estimate performance improvement
Cortex Code’s Response:
Root Cause Identified:
The model joins fact_transactions (now 180M rows) to dim_date without filtering first.
Line 47-52 in your SQL:
```sql
left join {{ ref('dim_date') }} d
on t.transaction_date = d.date_day
```
With 180M rows, this creates a massive intermediate result set before the WHERE clause on line 68.
Solution:
1. Move the date filter BEFORE the join (filter fact_transactions first)
2. Add clustering key on fact_transactions.transaction_date
3. Consider partitioning by month if queries typically filter by date range
Estimated improvement: 32 min → 6 min
Implementation:
-- Changed from this:
from {{ ref('fact_transactions') }} t
left join {{ ref('dim_date') }} d on t.transaction_date = d.date_day
where d.fiscal_year = 2024
-- To this:
from (
select * from {{ ref('fact_transactions') }}
where transaction_date >= '2024-01-01'
) t
left join {{ ref('dim_date') }} d on t.transaction_date = d.date_day
Plus added clustering:
{{ config(cluster_by=['transaction_date']) }}
Result: 32 minutes → 5.2 minutes. Problem solved in 20 minutes total.
Example 2: Pre-Launch Optimization
Scenario: Building a new mart_customer_churn_prediction model. Wanted to optimize it BEFORE the first production run.
I'm about to deploy this new dbt model to production. Please review and suggest optimizations BEFORE I run it for the first time.
Model: mart_customer_churn_prediction
Focus areas:
- Best materialization strategy (table, view, or incremental)
- Clustering key recommendations
- Potential bottlenecks in the SQL
- Incremental logic if applicable
- Query optimization opportunities
Here's the model SQL:
[pasted my model code]
Expected data volume: 50M+ customer records
Update frequency: Daily
Query pattern: Filtered by customer_segment and churn_date
Cortex Code’s Pre-Production Analysis:
Pre-Production Optimization Analysis:
CRITICAL ISSUES:
1. ❌ Using table materialization for 50M+ row result
Recommendation: Use incremental with unique_key on customer_id
2. ❌ No clustering key despite filtering on customer_segment and churn_date
Recommendation: cluster_by=['customer_segment', 'churn_date']
3. ❌ Complex CTE chain (7 CTEs) doing full table scans
Recommendation: Break into separate intermediate models
PERFORMANCE PREDICTIONS:
- As written: Estimated 45-60 minutes first run
- With optimizations: Estimated 8-12 minutes first run, 2-3 min incremental
SUGGESTED REFACTOR:
Split into 3 models:
1. int_customer_metrics (intermediate, incremental)
2. int_churn_features (intermediate, incremental)
3. mart_customer_churn_prediction (mart, incremental)
I implemented all suggestions. First production run: 9.3 minutes instead of the estimated 45-60.
Example 3: Monthly Performance Review
Every month, I do a comprehensive audit:
Step 1: Collect all metadata files
# My automation script copies these
cp ~/dbt_project/target/manifest.json ~/monthly_audits/2026-01/
cp ~/dbt_project/target/run_results.json ~/monthly_audits/2026-01/
Step 2: Upload to Snowflake
PUT file://~/monthly_audits/2026-01/* @dbt_metadata/monthly/2026-01/;
Step 3: Open Cortex Code and run monthly audit
Monthly dbt Performance Review - January 2026
Using files in dbt_metadata/monthly/2026-01/:
- manifest.json
- run_results.json
Provide comprehensive analysis:
1. HEALTH METRICS
- Overall project health score (0-100)
- Total models and average runtime
- Percentage using best practices (incremental, clustering)
- Month-over-month performance trend
2. TOP ISSUES
- 10 slowest models with root cause
- Performance anti-patterns detected
- Models that grew disproportionately
- Technical debt items
3. CLEANUP OPPORTUNITIES
- Unused or rarely-run models
- Outdated materializations
- Redundant transformations
- Models that can be archived
4. OPTIMIZATION ROADMAP
- Week-by-week action plan for next month
- Quick wins vs strategic improvements
- Estimated time savings and effort required
- Projected end-of-month performance
5. ROI CALCULATIONS
- Current monthly compute cost
- Potential savings from recommendations
- Effort/impact ratio for each item
January 2026 Audit Output:
dbt Project Health Score: 73/100 (Up from 61 last month)
PERFORMANCE SUMMARY:
- Total models: 147
- Average model runtime: 3.2 min (down from 5.1 min)
- Slowest model: dim_customer_360 (14.2 min)
- Models using incremental: 67% (target: 80%)
- Models with clustering: 45% (target: 70%)
TOP 10 ISSUES:
1. dim_customer_360 (14.2 min) - needs incremental + clustering
2. mart_sales_forecast (12.8 min) - complex window functions, consider simplification
3. fct_website_sessions (11.4 min) - full refresh daily, should be incremental
...
OPTIMIZATION ROADMAP - FEBRUARY 2026:
Week 1: Add clustering to 8 identified models (est. save 45 min/run)
Week 2: Convert 6 models to incremental (est. save 67 min/run)
Week 3: Refactor mart_sales_forecast (est. save 8 min/run)
Week 4: Remove 4 unused models identified
Projected end-of-month runtime: 58 minutes (current: 83 minutes)
Following this roadmap, I hit 61 minutes by month-end.
4.4: My Daily Workflow with Cortex Code
Here’s how Cortex Code fits into my actual workday:
Monday Morning (9:00 AM) – Weekly Review:
Upload latest manifest.json and run_results.json
Run performance audit
Create Jira tickets for top 3 optimization opportunities
Prioritize for the week
Tuesday-Thursday – Development:
Need a new model?
Ask Cortex Code to generate boilerplate
Review and customize for business logic
Ask Cortex to optimize before first run
Model running slow?
Share compiled SQL with Cortex
Get optimization suggestions
Implement and test
Friday Afternoon – Cleanup:
Review week’s changes in dbt
Ask Cortex to review my new models for anti-patterns
Generate documentation with Cortex assistance
Prepare for Monday’s review
Time saved per week:
Before: 8-10 hours on performance debugging
After: 1-2 hours on Cortex-assisted optimization
Net savings: 6-8 hours weekly
4.5: Prompts That Actually Work
Here are my most-used prompts, copy-paste ready:
Performance Analysis:
"Analyze this manifest.json and identify the top 10 slowest models with specific, actionable optimization recommendations ranked by estimated time savings."
"Compare these two run_results.json files (last week vs this week) and identify performance regressions, improvements, and new bottlenecks. Prioritize by impact."
"This model runs in X minutes. Here's the compiled SQL: [paste]. Provide optimization suggestions with estimated impact for each."
Model Optimization:
"Review this dbt model and suggest: 1) Best materialization strategy, 2) Clustering keys, 3) Incremental logic if applicable, 4) Query optimizations. Model: [paste]"
"I'm building a new model for [business purpose]. Suggest optimal dbt structure including staging, intermediate, and mart layers with proper materializations."
Debugging:
"This dbt model suddenly got slow. Root cause analysis based on: Compiled SQL: [paste], Recent changes: [describe], Data volume changes: [numbers]"
"Why is this incremental model doing full refreshes? Model config: [paste], Logs: [paste]"
Ongoing Monitoring:
"Monthly dbt health audit. Analyze manifest + run_results. Provide: health score, top 10 issues, optimization roadmap. Files: [paste]"
"Identify unused or rarely-run models in this manifest that could be archived. Criteria: run less than once per week, not referenced by marts."
4.6: What Works vs. What Doesn’t
After 3 months of daily use, here’s my honest assessment:
Performance impact in production (not just estimated)
4.7: Real Numbers from My Experience
Let me share the actual metrics that matter:
Before Cortex Code (December 2025):
dbt Performance:
Full refresh runtime: 2h 47min
Incremental runtime: 1h 15min
Models with clustering: 12/147 (8%)
Models using incremental: 42/147 (29%)
Airflow timeout failures: 2-3/week
My Time Spent:
Performance debugging: 8-10 hours/week
Manual manifest review: Never (too tedious)
Optimization work: Ad-hoc, reactive
New model development: 45-60 min per model
Costs:
Snowflake compute (dbt): ~$1,200/month
Airflow retries/failures: ~$180/month
My time opportunity cost: Unmeasured but significant
After 3 Months with Cortex Code (March 2026):
dbt Performance:
Full refresh runtime: 1h 23min (-50%)
Incremental runtime: 34min (-55%)
Models with clustering: 67/147 (46%)
Models using incremental: 99/147 (67%)
Airflow timeout failures: 1-2/month
My Time Spent:
Performance debugging: 1-2 hours/week (-85%)
Weekly manifest review: 15 min (automated with Cortex)
Optimization work: Systematic, proactive
New model development: 15-20 min per model (-67%)
Costs:
Snowflake compute (dbt): ~$680/month (-43%)
Airflow retries/failures: ~$35/month (-81%)
My time regained: 6-8 hours/week for feature development
ROI Calculation:
Cost of Cortex Code: Included in Snowflake Enterprise+ (no additional cost)
Monthly savings:
Snowflake compute: $520
Airflow compute: $145
My time (40 hours/month @ $75/hour): $3,000
Total: $3,665/month
Annual ROI: $43,980 in quantifiable savings
Plus unquantifiable benefits:
Faster feature delivery
Better data quality (more time for testing)
Reduced incidents and pages
Improved team morale (less firefighting)
Part 5: Quick Wins – Other Tools
While dbt is where I get the most value, Cortex Code is useful for other data engineering tools too:
5.1: Airflow DAGs
Quick generation using Cortex Code interface:
Generate a production-ready Airflow DAG for my daily dbt run:
Requirements:
- Schedule: Run daily at 2 AM UTC
- Retry logic: 3 attempts with 5-minute delay between retries
- Send Slack alert on failure (webhook already configured)
- Trigger downstream Tableau refresh on success
- Include SLA monitoring (alert if takes >90 minutes)
- Use dbt Cloud operator
- Handle task dependencies properly
Python version: 3.9
Airflow version: 2.7
Cortex Code generates:
from airflow import DAG
from airflow.operators.bash import BashOperator
from airflow.operators.python import PythonOperator
from airflow.providers.slack.notifications.slack import send_slack_notification
from datetime import datetime, timedelta
default_args = {
'owner': 'data-engineering',
'depends_on_past': False,
'email_on_failure': False,
'retries': 3,
'retry_delay': timedelta(minutes=5),
'sla': timedelta(minutes=90),
}
dag = DAG(
'daily_dbt_run',
default_args=default_args,
description='Daily dbt production run',
schedule='0 2 * * *', # 2 AM UTC daily
start_date=datetime(2026, 1, 1),
catchup=False,
on_failure_callback=send_slack_notification(
text='❌ dbt DAG failed!',
channel='#data-alerts'
),
)
dbt_run = BashOperator(
task_id='dbt_run',
bash_command='cd /opt/dbt && dbt run --profiles-dir .',
dag=dag,
)
dbt_test = BashOperator(
task_id='dbt_test',
bash_command='cd /opt/dbt && dbt test --profiles-dir .',
dag=dag,
)
refresh_tableau = BashOperator(
task_id='refresh_tableau',
bash_command='curl -X POST https://tableau-server/api/refresh',
dag=dag,
)
dbt_run >> dbt_test >> refresh_tableau
Gets you 80% of the way there in 30 seconds vs. 30 minutes of boilerplate typing.
5.2: Streamlit Dashboards
Dashboard scaffolding with Cortex Code:
Create a Streamlit dashboard for sales analytics:
Features needed:
- Date range filter (last 7, 30, 90 days or custom)
- KPI cards showing: Total Revenue, Total Orders, Average Order Value
- Line chart: Daily revenue trend over selected period
- Bar chart: Top 10 products by revenue
- Data table: Recent orders with filters
- Connect to Snowflake table: analytics.mart_daily_sales
- Use Streamlit's modern layout with columns
- Include data refresh timestamp
- Add export to CSV button
Make it production-ready with proper error handling.
Cortex Code generates:
import streamlit as st
import snowflake.connector
import pandas as pd
import plotly.express as px
from datetime import datetime, timedelta
st.set_page_config(page_title="Sales Analytics", layout="wide")
# Snowflake connection
@st.cache_resource
def get_connection():
return snowflake.connector.connect(
user=st.secrets["snowflake"]["user"],
password=st.secrets["snowflake"]["password"],
account=st.secrets["snowflake"]["account"],
warehouse='ANALYTICS_WH',
database='ANALYTICS',
schema='MART'
)
# Main dashboard
st.title("📊 Sales Analytics Dashboard")
# Date filter
col1, col2 = st.columns([3, 1])
with col1:
date_range = st.selectbox(
"Select Period",
["Last 7 Days", "Last 30 Days", "Last 90 Days", "Custom"]
)
# ... [rest of dashboard code]
Generates working dashboard layout. Still need to refine styling and business logic, but saves 45 minutes of setup.
(Keeping these brief since the focus is dbt – but both are genuinely useful)
Part 6: Practical Tips for Data Engineers
The Learning Curve
Week 1: Feels magical but you don’t trust it
Generate code, read every line carefully
Validate everything in dev
Probably slower than writing manually
Week 2-4: Building confidence
Start recognizing patterns in good vs. questionable output
Develop your own prompt templates
20-30% faster than before
Month 2+: It’s part of your workflow
Know when to use it vs. when to write manually
Can spot hallucinations immediately
50-70% faster on routine tasks
My Validation Checklist
Before deploying Cortex-generated code:
✅ Logic review: Does this make business sense?
✅ Performance check: Run EXPLAIN on generated SQL
✅ Edge cases: Test with null values, duplicates, empty sets
✅ Incremental logic: Validate deduplication and update logic
✅ Dependencies: Check for circular references
✅ Tests: Generated code needs generated tests
✅ Peer review: Treat AI code like any other PR
Learning new concepts (defeats the learning purpose)
Sometimes use for:
Debugging (helpful but verify root cause)
Refactoring (good starting point, heavy review)
Documentation (generates good drafts)
Always use for:
Boilerplate (staging models, tests, yml)
Performance analysis (manifest reviews)
Exploration (trying new patterns)
Part 7: The Honest Verdict
For dbt Specifically:
Model Generation: 8/10
Great for standard patterns
Saves typing, enforces conventions
Still need to add business logic
Test Creation: 9/10
Covers standard tests well
Good at identifying what to test
Custom tests need review
Manifest Analysis: 10/10 ⭐⭐⭐
This alone justifies using Cortex Code
Finds issues I’d never spot manually
Actionable, prioritized recommendations
Performance Optimization: 9/10
Suggestions are usually right
Massive time savings
Estimates are reasonably accurate
Macro Writing: 7/10
Good starting point
Logic sometimes over-complicated
Requires Jinja knowledge to review properly
Documentation: 8/10
Generates good yml drafts
Descriptions are generic but fixable
Saves tons of tedious typing
Overall Assessment:
Is Cortex Code worth it for data engineers?
Absolutely yes, with caveats:
✅ Use it if you:
Work with dbt daily
Have performance challenges
Want to spend less time on boilerplate
Value systematic optimization over guesswork
Are comfortable reviewing and validating AI output
⚠️ Be cautious if you:
Are still learning dbt (use it, but understand what it generates)
Have highly specialized/unusual patterns
Work in heavily regulated industry (extra validation needed)
Have very small dbt projects (<20 models – manual is fine)
❌ Skip it if you:
Don’t have Snowflake Enterprise+
Rarely write dbt code
Prefer full manual control (totally valid!)
The Real Value Proposition
It’s not about writing code faster (though that’s nice).
It’s about:
Systematic performance optimization instead of guesswork
Proactive monitoring instead of reactive firefighting
Data-driven decisions about what to optimize
Consistent code quality through enforced best practices
More time for high-value work instead of debugging
My Recommendation
Start small:
Week 1: Try manifest analysis only
Week 2: Generate a few staging models
Week 3: Use for performance debugging
Week 4: Incorporate into daily workflow
By month 2, you’ll wonder how you lived without it.
Conclusion: The Tool That Changed My Workflow
Three months ago, I was drowning in performance issues, spending my days debugging slow dbt models and my nights fixing Airflow timeouts.
Today, my dbt runs 48% faster, I spend 85% less time on performance debugging, and I actually have time to build new features instead of constantly firefighting.
Cortex Code didn’t just make me faster—it made me smarter about optimization. The manifest analysis taught me patterns I now recognize manually. The performance suggestions showed me best practices I’d never considered.
Is it perfect? No. Does it replace data engineering expertise? Definitely not. But used correctly, with proper validation and critical thinking, it’s become as essential to my workflow as dbt itself.
If you’re a data engineer using Snowflake and dbt, try the manifest analysis feature today. Upload your manifest.json, ask for performance recommendations, and see what it finds. I bet you’ll be shocked—I was.
And if you do try it, let me know what you discover. I’m always curious what performance wins other engineers are finding.
Now go optimize something. Your Airflow DAG will thank you.
Snowflake Cortex AI matured significantly between 2023-2026, expanding from simple LLM functions to a comprehensive AI platform with AISQL, Cortex Search, Cortex Analyst, Document AI, and Agents. As adoption accelerates, controlling costs becomes critical—not because Cortex is expensive, but because its pricing model differs fundamentally from traditional Snowflake compute.
This guide breaks down exactly how Snowflake charges for Cortex, compares pricing models, provides real cost scenarios, and shares optimization strategies based on 2026 current rates.
What is Snowflake Cortex AI? (2026 Overview)
Snowflake Cortex AI is a suite of integrated generative AI Cortex AI capabilities built directly into Snowflake. Instead of exporting data to external APIs, you can invoke LLM functions, embeddings, search, and agents directly in SQL—keeping data within Snowflake’s security perimeter while dramatically reducing latency and complexity.
The key difference from traditional Snowflake compute: Cortex charges on token consumption, not compute credits.
AISQL functions let you call AI models directly in SQL. These are the most commonly used Cortex features.
What Are the Available AISQL Functions?
Available functions include AI_COMPLETE, AI_CLASSIFY, AI_FILTER, AI_AGG, AI_EMBED, AI_EXTRACT, AI_SENTIMENT, AI_SIMILARITY, AI_TRANSCRIBE, AI_PARSE_DOCUMENT, AI_REDACT, and AI_TRANSLATE.
AI_SENTIMENT: Analyzing Emotional Tone
How Does AI_SENTIMENT Work?
AI_SENTIMENT analyzes text and returns sentiment classification.
Real SQL example:
sql
SELECT
review_id,
review_text,
SNOWFLAKE.CORTEX.AI_SENTIMENT(review_text) as sentiment_score
FROM product_reviews
WHERE review_date >= CURRENT_DATE - 30;
Cost profile:
Input tokens: Review text (avg 120 tokens)
Output tokens: Sentiment value (2-3 tokens)
Total per row: ~125 tokens
Cost by volume (using Llama 3.1 8B, smallest model):
Volume
Monthly Cost
10,000 reviews
~$0.30
100,000 reviews
~$3.00
1,000,000 reviews
~$30.00
Why sentiment is cost-efficient: High input-to-output ratio. You send large amounts of text but receive minimal response.
AI_EXTRACT: Pulling Structured Data
What Does AI_EXTRACT Do?
Extracts specific structured information from unstructured text.
Real SQL example:
sql
SELECT
ticket_id,
email_body,
SNOWFLAKE.CORTEX.AI_EXTRACT(
email_body,
'Extract customer issue, resolution requested, and priority level'
) as extracted_fields
FROM support_tickets
WHERE status = 'unresolved';
Cost profile:
Input tokens: Unstructured text (avg 350 tokens)
Output tokens: Extracted data (50-100 tokens)
Total per call: ~425 tokens
Cost by volume (using Snowflake Arctic, mid-tier):
Volume
Monthly Cost
1,000 extractions
~$0.51
10,000 extractions
~$5.10
100,000 extractions
~$51.00
Key insight: Extraction provides excellent token efficiency—you’re converting unstructured data into structured format without massive output expansion.
AI_COMPLETE: General Text Generation
When Do You Use AI_COMPLETE?
Generates new text based on prompts—the most expensive function due to output token generation.
Real SQL example:
sql
SELECT
review_id,
SNOWFLAKE.CORTEX.AI_COMPLETE(
'mistral-large',
'Write a 2-sentence response to this customer feedback: ' || feedback_text
) as generated_response
FROM customer_feedback
WHERE rating < 3;
Cost profile:
Input tokens: Prompt + context (avg 180 tokens)
Output tokens: Generated text (varies by request, 30-150 tokens)
Total per call: ~210-330 tokens
Cost by output length (using Mistral Large, premium model):
Output Length
Per Call
10,000 Calls/Month
30 tokens (2 sentences)
$0.0015
$15.00
100 tokens (1 paragraph)
$0.0034
$34.00
250 tokens (1 page)
$0.0081
$81.00
Critical factor: Output length directly multiplies costs. Requesting brief, specific responses is essential.
AI_CLASSIFY: Multi-Label Text Classification
How Does AI_CLASSIFY Work?
Categorizes text into predefined classes.
Real SQL example:
sql
SELECT
ticket_id,
description,
SNOWFLAKE.CORTEX.AI_CLASSIFY(
description,
'Classify as: billing, technical, account, refund, or other'
) as category
FROM support_tickets;
Cost profile:
Input tokens: Text content (avg 200 tokens)
Output tokens: Category label (1-5 tokens)
Total per call: ~205 tokens
Cost by volume (using Llama 3.1 8B):
Volume
Monthly Cost
10,000 classifications
~$0.61
100,000 classifications
~$6.10
Why it’s cheap: Classification is low-computation with minimal output.
Example: 50GB index × 6.3 credits/GB/month = 315 credits (~$945/month)
Storage:
Standard Snowflake rates (~$23/TB/month)
Example: 50GB = $1.15/month
Total monthly cost example:
Initial setup: $750 (one-time)
Ongoing monthly: $946
Annual: ~$11,352
When Cortex Search makes sense: Large document collections where semantic search provides business value justifying the cost.
Cortex Analyst: Natural Language to SQL
How is Cortex Analyst Priced?
Fixed cost per natural language question.
Pricing:
6.7 credits per 100 messages
1 message = 1 natural language question
Only successful responses charged (HTTP 200)
Cost examples:
Questions
Monthly Cost
100
$20
1,000
$201
10,000
$2,010
Key point: Message cost is fixed; underlying SQL query execution charges additional compute credits based on warehouse complexity.
Real-World Cost Scenarios (2026)
Scenario 1: E-Commerce Sentiment Analysis
Setup: 200,000 product reviews/month
sql
SELECT
review_id,
SNOWFLAKE.CORTEX.AI_SENTIMENT(review_text, 'llama2-70b-chat') as sentiment,
SNOWFLAKE.CORTEX.AI_EXTRACT(review_text, 'Extract main product issue') as issue
FROM reviews;
SELECT
ticket_id,
SNOWFLAKE.CORTEX.AI_CLASSIFY(description, 'category') as category,
SNOWFLAKE.CORTEX.AI_EXTRACT(description, 'Extract issue and resolution') as details,
SNOWFLAKE.CORTEX.AI_COMPLETE('mistral-large', 'Draft response: ' || description, {}) as response
FROM tickets;
Cost breakdown:
Function
Volume
Tokens/Call
Model
Cost
Classification
5,000
150
Llama
$0.23
Extraction
5,000
300
Arctic
$0.90
Response Gen
2,500
200
Mistral
$1.80
Total
–
–
–
$2.93/month
Annual cost: $35.16
Scenario 3: Document Processing
Setup: 500 PDFs/month (avg 3,000 tokens each)
sql
SELECT
doc_id,
SNOWFLAKE.CORTEX.AI_PARSE_DOCUMENT(@stage, 'LAYOUT') as parsed_content
FROM documents;
What’s the difference between AISQL and Cortex Search costs?
AISQL functions charge per token processed (input + output), while Cortex Search charges for embedding tokens during creation and ongoing serving costs per GB of index maintained. AISQL is cheaper for casual use; Cortex Search makes sense for high-volume semantic search.
Which model should I choose to minimize costs?
Model choice is your biggest cost lever (10x variation possible):
Use Llama 3.1 8B for:
Sentiment analysis
Basic classification
Simple extraction
Any routine task
Cost: 80% cheaper than premium models Quality: Excellent for classification/routine tasks
Use Arctic for:
Complex extractions
Entity recognition
Moderate-complexity analysis
Conversational responses
Cost: 60% cheaper than premium Quality: Excellent overall performance
Use premium (GPT-4, Claude Opus) only for:
Complex reasoning
Code generation
Nuanced analysis requiring explanations
Real-time conversational systems
Example: Sentiment analysis works equally well with Llama ($3/month for 100k reviews) vs. Claude ($60/month for same work). Same business outcome, 20x cost difference.
How do I estimate costs before processing large volumes?
Step-by-step approach:
Sample your data:
sql
SELECT
SNOWFLAKE.CORTEX.COUNT_TOKENS(your_column) as token_count
FROM your_table
LIMIT 1000;
Calculate average tokens:
sql
SELECT
AVG(token_count) as avg_tokens,
COUNT(*) as sample_size
FROM (
SELECT SNOWFLAKE.CORTEX.COUNT_TOKENS(your_column) as token_count
FROM your_table
LIMIT 1000
);
Snowflake provides the CORTEX_FUNCTIONS_USAGE_HISTORY view for aggregated hourly usage data that groups token and credit consumption by function, model, and hour.
sql
SELECT
DATE_TRUNC('day', START_TIME) as day,
FUNCTION_NAME,
MODEL_NAME,
SUM(TOKENS_USED) as total_tokens,
SUM(CREDITS_USED) as total_credits,
ROUND(SUM(CREDITS_USED) * 3.5, 2) as estimated_cost
FROM SNOWFLAKE.ACCOUNT_USAGE.CORTEX_FUNCTIONS_USAGE_HISTORY
WHERE START_TIME >= CURRENT_DATE - 30
GROUP BY DATE_TRUNC('day', START_TIME), FUNCTION_NAME, MODEL_NAME
ORDER BY day DESC;
Is Cortex cheaper than OpenAI API?
Yes, significantly:
Provider
Input Cost
Output Cost
Advantage
OpenAI GPT-4
$0.03/1K tokens
$0.06/1K tokens
Baseline
Mistral Large (via API)
$0.003/1K tokens
$0.009/1K tokens
10x cheaper
Snowflake Arctic
$0.0012/1K tokens
$0.0036/1K tokens
25x cheaper
Snowflake Llama 3.1
$0.0005/1K tokens
$0.0015/1K tokens
40x cheaper
Plus: No separate API authentication, no data exfiltration, no rate limiting concerns.
When NOT to Use Cortex Functions
Avoid Cortex for String Matching
sql
-- DON'T DO THIS (costs money)
SELECT SNOWFLAKE.CORTEX.AI_CLASSIFY(
email_body,
'Does this contain "refund"? Yes or No'
)
-- DO THIS (free)
SELECT CASE
WHEN email_body ILIKE '%refund%' THEN 'Yes'
ELSE 'No'
END;
Avoid Cortex for Structured Lookups
sql
-- DON'T DO THIS (costs money)
SELECT SNOWFLAKE.CORTEX.AI_COMPLETE(
'mistral-large',
'What is customer name for ID 12345?'
);
-- DO THIS (free)
SELECT name FROM customers WHERE id = 12345;
Avoid Cortex for Deterministic Operations
sql
-- DON'T DO THIS (costs money)
SELECT SNOWFLAKE.CORTEX.AI_COMPLETE(
'mistral-large',
'Convert 01/15/2026 from MM/DD/YYYY to YYYY-MM-DD'
);
-- DO THIS (free)
SELECT TO_DATE('01/15/2026', 'MM/DD/YYYY');
Cost Optimization Best Practices
Optimization 1: Model Selection by Task
Choose the smallest model that works:
sql
-- BEFORE: Sentiment with premium model
SELECT SNOWFLAKE.CORTEX.AI_SENTIMENT(
review_text,
'claude-opus' -- Most expensive
) as sentiment;
-- AFTER: Sentiment with budget model
SELECT SNOWFLAKE.CORTEX.AI_SENTIMENT(
review_text,
'llama2-70b-chat' -- Cheapest, 90% as accurate
) as sentiment;
Result: 80% cost reduction for identical accuracy on classification tasks.
Optimization 2: Aggressive Caching
Don’t recompute results:
sql
CREATE OR REPLACE DYNAMIC TABLE cached_sentiments AS
SELECT
review_id,
SNOWFLAKE.CORTEX.AI_SENTIMENT(review_text) as sentiment,
CURRENT_TIMESTAMP as processed_at
FROM product_reviews
WHERE created_date >= CURRENT_DATE - 30;
-- Query cache instead of recomputing
SELECT * FROM cached_sentiments
WHERE sentiment < -0.5;
-- Process all at once (low overhead)
CREATE TASK process_batch_daily
WAREHOUSE = compute_wh
SCHEDULE = 'USING CRON 0 2 * * * UTC'
AS
SELECT SNOWFLAKE.CORTEX.AI_SENTIMENT(text)
FROM data_queue
WHERE processed = false;
Result: 15-20% reduction in compute overhead.
Optimization 5: Input Data Cleaning
sql
-- Clean data before processing
CREATE FUNCTION clean_text(raw_text VARCHAR)
RETURNS VARCHAR
AS
$$
SELECT REGEXP_REPLACE(
REGEXP_REPLACE(raw_text, '(\[.*?\])', ''), -- Remove metadata
'\n\n+', ' ' -- Collapse newlines
)
$$;
-- Process clean data only
SELECT SNOWFLAKE.CORTEX.AI_SENTIMENT(clean_text(messy_input))
FROM raw_data;
The Night Everything Broke (And How Streams Saved Me)
It was 2 AM on a Tuesday. My phone was buzzing non-stop. Our nightly ETL job had failed—again. This time, it crashed after processing 6 hours of data, and we had to start over from scratch. The business needed fresh customer data by 8 AM for the morning reports.
I was running a classic batch process: every night at midnight, truncate the target table, reload everything from source, rebuild all the aggregations. It worked fine when we had 100,000 customers. But we’d grown to 5 million customers, and the full reload was taking 8 hours.
That’s when I discovered Streams and Tasks in Snowflake. Within a week, I rebuilt the entire pipeline:
No more full reloads (only process changes)
No more manual scheduling (Tasks handled it)
No more 8-hour batch windows (incremental updates took 10 minutes)
No more 2 AM phone calls (built-in retry logic)
This guide is everything I wish someone had shown me that night. We’ll build real pipelines—not toy examples—starting from simple automation and working up to complex patterns like SCD Type 2.
What Are Streams and Tasks? (The Simple Explanation)
Before diving into code, let’s understand what these actually do:
Streams are like security cameras for your tables. They watch what changes (inserts, updates, deletes) and create a “change log” you can query. Think of it as automatic change data capture (CDC) built into Snowflake.
Tasks are scheduled SQL jobs. They’re like cron jobs but smarter—they can depend on other tasks, run only when data is available, and auto-retry on failure.
Together? Magic. Streams detect changes, Tasks process them automatically.
The old way:
-- Run this manually or via cron at 2 AM
TRUNCATE TABLE customer_summary;
INSERT INTO customer_summary
SELECT customer_id, COUNT(*) as order_count, SUM(amount) as total_spent
FROM orders
GROUP BY customer_id;
-- Takes hours, processes everything, fails if interrupted
The new way:
-- Stream watches for changes
CREATE STREAM order_changes ON TABLE orders;
-- Task processes only changes, runs automatically
CREATE TASK update_customer_summary
SCHEDULE = '5 MINUTE'
WHEN SYSTEM$STREAM_HAS_DATA('order_changes')
AS
-- Process only changed orders (10 seconds instead of 8 hours!)
MERGE INTO customer_summary ...
Let’s build this properly.
Part 1: Understanding Streams (Change Data Capture)
Creating Your First Stream
-- Setup: Create sample source table
CREATE OR REPLACE TABLE customers (
customer_id INTEGER,
customer_name STRING,
email STRING,
status STRING,
created_date DATE,
updated_at TIMESTAMP_LTZ DEFAULT CURRENT_TIMESTAMP()
);
-- Insert initial data
INSERT INTO customers VALUES
(1, 'John Doe', '[email protected]', 'ACTIVE', '2024-01-15', CURRENT_TIMESTAMP()),
(2, 'Jane Smith', '[email protected]', 'ACTIVE', '2024-02-20', CURRENT_TIMESTAMP()),
(3, 'Bob Johnson', '[email protected]', 'ACTIVE', '2024-03-10', CURRENT_TIMESTAMP());
-- Create stream to track changes
CREATE OR REPLACE STREAM customer_changes ON TABLE customers;
-- At this point, stream is empty (no changes yet)
SELECT * FROM customer_changes;
-- Returns 0 rows
How Streams Capture Changes
Now let’s make some changes and see what the stream captures:
-- Make various changes
UPDATE customers SET status = 'INACTIVE' WHERE customer_id = 1;
INSERT INTO customers VALUES (4, 'Alice Williams', '[email protected]', 'ACTIVE', '2024-04-05', CURRENT_TIMESTAMP());
DELETE FROM customers WHERE customer_id = 3;
-- Query the stream
SELECT
customer_id,
customer_name,
email,
status,
METADATA$ACTION, -- INSERT, DELETE, or UPDATE
METADATA$ISUPDATE, -- TRUE for updates
METADATA$ROW_ID -- Unique identifier for this change
FROM customer_changes;
Output:
customer_id | customer_name | status | METADATA$ACTION | METADATA$ISUPDATE
1 | John Doe | INACTIVE | INSERT | TRUE
1 | John Doe | ACTIVE | DELETE | TRUE
4 | Alice Williams | ACTIVE | INSERT | FALSE
3 | Bob Johnson | ACTIVE | DELETE | FALSE
Understanding the output:
UPDATE appears as DELETE (old value) + INSERT (new value) with METADATA$ISUPDATE = TRUE
INSERT appears as INSERT with METADATA$ISUPDATE = FALSE
DELETE appears as DELETE with METADATA$ISUPDATE = FALSE
Stream Consumption (Critical Concept)
Here’s something that confused me for weeks: streams are consumed when you read from them in a DML operation.
-- Query stream (doesn't consume)
SELECT * FROM customer_changes;
-- Stream still has data-- Use stream in INSERT (consumes!)
INSERT INTO customer_backup
SELECT * FROM customer_changes;
-- Query stream again
SELECT * FROM customer_changes;
-- Returns 0 rows - stream was consumed!
Important patterns:
-- If you need the data multiple times, capture it first
CREATE TEMPORARY TABLE changes_snapshot AS
SELECT * FROM customer_changes;
-- Now use snapshot multiple times
INSERT INTO target1 SELECT * FROM changes_snapshot;
INSERT INTO target2 SELECT * FROM changes_snapshot;
-- Stream is only consumed once
Part 2: Understanding Tasks (Automation)
Creating Your First Task
-- Simple task that runs on schedule
CREATE OR REPLACE TASK hello_world_task
WAREHOUSE = my_wh
SCHEDULE = '5 MINUTE'
AS
INSERT INTO task_logs
VALUES ('Hello from task!', CURRENT_TIMESTAMP());
-- Tasks are created in SUSPENDED state-- You must explicitly start them
ALTER TASK hello_world_task RESUME;
-- Check task status
SHOW TASKS LIKE 'hello_world_task';
-- View task runs
SELECT
name,
state,
scheduled_time,
completed_time,
error_message
FROM TABLE(INFORMATION_SCHEMA.TASK_HISTORY())
WHERE name = 'HELLO_WORLD_TASK'
ORDER BY scheduled_time DESC
LIMIT 10;
Conditional Execution (Run Only When Needed)
-- Create task that only runs when stream has data
CREATE OR REPLACE TASK process_customer_changes
WAREHOUSE = etl_wh
SCHEDULE = '5 MINUTE'
WHEN SYSTEM$STREAM_HAS_DATA('customer_changes')
AS
INSERT INTO customer_history
SELECT
customer_id,
customer_name,
email,
status,
METADATA$ACTION as change_type,
CURRENT_TIMESTAMP() as processed_at
FROM customer_changes;
ALTER TASK process_customer_changes RESUME;
Why this is powerful:
Task checks every 5 minutes
Only runs if stream has data
Warehouse only spins up when needed
Zero cost if no changes
Task Dependencies (Building Pipelines)
-- Create a pipeline: raw → staging → production-- Task 1: Load raw data
CREATE OR REPLACE TASK load_raw_data
WAREHOUSE = etl_wh
SCHEDULE = '10 MINUTE'
AS
COPY INTO raw_orders
FROM @s3_stage/orders/
FILE_FORMAT = (TYPE = 'CSV');
-- Task 2: Clean and stage (runs after Task 1)
CREATE OR REPLACE TASK stage_data
WAREHOUSE = etl_wh
AFTER load_raw_data -- Dependency!
AS
INSERT INTO staged_orders
SELECT
order_id,
customer_id,
UPPER(TRIM(product_name)) as product_name,
amount,
order_date
FROM raw_orders_stream
WHERE amount > 0; -- Filter bad data-- Task 3: Aggregate to production (runs after Task 2)
CREATE OR REPLACE TASK aggregate_to_prod
WAREHOUSE = etl_wh
AFTER stage_data -- Another dependency!
AS
MERGE INTO customer_summary target
USING (
SELECT
customer_id,
COUNT(*) as new_orders,
SUM(amount) as new_amount
FROM staged_orders_stream
GROUP BY customer_id
) source
ON target.customer_id = source.customer_id
WHEN MATCHED THEN
UPDATE SET
total_orders = total_orders + source.new_orders,
total_spent = total_spent + source.new_amount
WHEN NOT MATCHED THEN
INSERT (customer_id, total_orders, total_spent)
VALUES (source.customer_id, source.new_orders, source.new_amount);
-- IMPORTANT: Resume tasks in reverse order (child first, parent last)
ALTER TASK aggregate_to_prod RESUME;
ALTER TASK stage_data RESUME;
ALTER TASK load_raw_data RESUME; -- Root task last!
Part 3: Real Use Case #1 – Simple Incremental Load
Scenario: Load customer orders from source system, keep only net changes.
-- Source table (simulates external system)
CREATE OR REPLACE TABLE source_orders (
order_id INTEGER,
customer_id INTEGER,
product_name STRING,
amount DECIMAL(10,2),
order_date DATE,
updated_at TIMESTAMP_LTZ DEFAULT CURRENT_TIMESTAMP()
);
-- Target table (your data warehouse)
CREATE OR REPLACE TABLE dwh_orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER,
product_name STRING,
amount DECIMAL(10,2),
order_date DATE,
loaded_at TIMESTAMP_LTZ
);
-- Create stream on source
CREATE OR REPLACE STREAM source_orders_stream ON TABLE source_orders;
-- Create incremental load task
CREATE OR REPLACE TASK incremental_load_orders
WAREHOUSE = etl_wh
SCHEDULE = '5 MINUTE'
WHEN SYSTEM$STREAM_HAS_DATA('source_orders_stream')
AS
MERGE INTO dwh_orders target
USING (
-- Get net changes from stream
SELECT
order_id,
customer_id,
product_name,
amount,
order_date
FROM source_orders_stream
WHERE METADATA$ACTION = 'INSERT'
AND METADATA$ISUPDATE = FALSE
) source
ON target.order_id = source.order_id
WHEN MATCHED THEN
UPDATE SET
target.customer_id = source.customer_id,
target.product_name = source.product_name,
target.amount = source.amount,
target.order_date = source.order_date,
target.loaded_at = CURRENT_TIMESTAMP()
WHEN NOT MATCHED THEN
INSERT (order_id, customer_id, product_name, amount, order_date, loaded_at)
VALUES (source.order_id, source.customer_id, source.product_name,
source.amount, source.order_date, CURRENT_TIMESTAMP());
ALTER TASK incremental_load_orders RESUME;
-- Test it!
INSERT INTO source_orders VALUES
(1, 101, 'Widget A', 29.99, '2026-01-15', CURRENT_TIMESTAMP()),
(2, 102, 'Widget B', 49.99, '2026-01-16', CURRENT_TIMESTAMP());
-- Wait 5 minutes, check target
SELECT * FROM dwh_orders;
-- Make updates
UPDATE source_orders SET amount = 39.99 WHERE order_id = 1;
-- Wait 5 minutes, verify update applied
SELECT * FROM dwh_orders WHERE order_id = 1;
Why this works:
Stream captures all changes
Task runs only when changes exist
MERGE handles both new and updated records
Fully automated, zero manual intervention
Part 4: Real Use Case #2 – SCD Type 2 (The Big One)
This is the use case everyone asks about. Slowly Changing Dimensions Type 2 tracks full history of changes.
Business requirement: Track complete history of customer data changes over time.
Step 1: Create SCD2 Table Structure
-- Dimension table with SCD2 pattern
CREATE OR REPLACE TABLE dim_customer_scd2 (
customer_key INTEGER AUTOINCREMENT, -- Surrogate key
customer_id INTEGER, -- Natural key
customer_name STRING,
email STRING,
phone STRING,
address STRING,
city STRING,
state STRING,
status STRING,
effective_start_date TIMESTAMP_LTZ, -- When this version became active
effective_end_date TIMESTAMP_LTZ, -- When this version became inactive
is_current BOOLEAN, -- Is this the current version?
inserted_at TIMESTAMP_LTZ DEFAULT CURRENT_TIMESTAMP()
);
-- Source table
CREATE OR REPLACE TABLE source_customers (
customer_id INTEGER PRIMARY KEY,
customer_name STRING,
email STRING,
phone STRING,
address STRING,
city STRING,
state STRING,
status STRING,
updated_at TIMESTAMP_LTZ DEFAULT CURRENT_TIMESTAMP()
);
-- Load initial data
INSERT INTO source_customers VALUES
(1, 'John Doe', '[email protected]', '555-0001', '123 Main St', 'Seattle', 'WA', 'ACTIVE', CURRENT_TIMESTAMP()),
(2, 'Jane Smith', '[email protected]', '555-0002', '456 Oak Ave', 'Portland', 'OR', 'ACTIVE', CURRENT_TIMESTAMP()),
(3, 'Bob Johnson', '[email protected]', '555-0003', '789 Pine Rd', 'Boston', 'MA', 'ACTIVE', CURRENT_TIMESTAMP());
-- Initial load to dimension
INSERT INTO dim_customer_scd2
(customer_id, customer_name, email, phone, address, city, state, status,
effective_start_date, effective_end_date, is_current)
SELECT
customer_id,
customer_name,
email,
phone,
address,
city,
state,
status,
CURRENT_TIMESTAMP() as effective_start_date,
'9999-12-31'::TIMESTAMP_LTZ as effective_end_date,
TRUE as is_current
FROM source_customers;
-- Verify
SELECT * FROM dim_customer_scd2;
Step 2: Create Stream on Source
CREATE OR REPLACE STREAM source_customers_stream ON TABLE source_customers;
Step 3: Build SCD2 Processing Logic
This is the complex part. We need to:
Identify what changed
Expire old records (set end date, is_current = FALSE)
Insert new versions
CREATE OR REPLACE TASK process_customer_scd2
WAREHOUSE = etl_wh
SCHEDULE = '10 MINUTE'
WHEN SYSTEM$STREAM_HAS_DATA('source_customers_stream')
AS
BEGIN
-- Step 1: Expire old records for changed customers
UPDATE dim_customer_scd2
SET
effective_end_date = CURRENT_TIMESTAMP(),
is_current = FALSE
WHERE customer_id IN (
SELECT customer_id
FROM source_customers_stream
WHERE METADATA$ACTION = 'INSERT' -- Updates appear as INSERT in stream
AND METADATA$ISUPDATE = TRUE
)
AND is_current = TRUE;
-- Step 2: Insert new versions for changed customers
INSERT INTO dim_customer_scd2
(customer_id, customer_name, email, phone, address, city, state, status,
effective_start_date, effective_end_date, is_current)
SELECT
customer_id,
customer_name,
email,
phone,
address,
city,
state,
status,
CURRENT_TIMESTAMP() as effective_start_date,
'9999-12-31'::TIMESTAMP_LTZ as effective_end_date,
TRUE as is_current
FROM source_customers_stream
WHERE METADATA$ACTION = 'INSERT'
AND METADATA$ISUPDATE = TRUE;
-- Step 3: Insert brand new customers
INSERT INTO dim_customer_scd2
(customer_id, customer_name, email, phone, address, city, state, status,
effective_start_date, effective_end_date, is_current)
SELECT
customer_id,
customer_name,
email,
phone,
address,
city,
state,
status,
CURRENT_TIMESTAMP() as effective_start_date,
'9999-12-31'::TIMESTAMP_LTZ as effective_end_date,
TRUE as is_current
FROM source_customers_stream
WHERE METADATA$ACTION = 'INSERT'
AND METADATA$ISUPDATE = FALSE;
END;
ALTER TASK process_customer_scd2 RESUME;
Step 4: Test SCD2 Processing
-- Test 1: Update customer address (should create new version)
UPDATE source_customers
SET address = '999 New Street', city = 'San Francisco', state = 'CA'
WHERE customer_id = 1;
-- Wait 10 minutes (or manually run: EXECUTE TASK process_customer_scd2;)-- Check results - should see 2 versions of customer 1
SELECT
customer_key,
customer_id,
customer_name,
address,
city,
state,
effective_start_date,
effective_end_date,
is_current
FROM dim_customer_scd2
WHERE customer_id = 1
ORDER BY effective_start_date;
-- Output:-- customer_key | customer_id | address | city | is_current | effective_start_date | effective_end_date-- 1 | 1 | 123 Main St | Seattle | FALSE | 2026-01-15 10:00 | 2026-01-15 15:30-- 4 | 1 | 999 New Street | San Francisco | TRUE | 2026-01-15 15:30 | 9999-12-31 23:59
-- Test 2: Update multiple attributes
UPDATE source_customers
SET
email = '[email protected]',
phone = '555-9999',
status = 'INACTIVE'
WHERE customer_id = 2;
-- Check history
SELECT
customer_key,
customer_id,
customer_name,
email,
phone,
status,
effective_start_date,
is_current
FROM dim_customer_scd2
WHERE customer_id = 2
ORDER BY effective_start_date;
-- Test 3: Insert new customer
INSERT INTO source_customers VALUES
(4, 'Alice Williams', '[email protected]', '555-0004', '321 Elm St', 'Austin', 'TX', 'ACTIVE', CURRENT_TIMESTAMP());
-- Verify new customer appears in dimension
SELECT * FROM dim_customer_scd2 WHERE customer_id = 4;
Step 5: Query Historical Data
Now the payoff—querying data as it was at any point in time:
-- Current state (easy)
SELECT * FROM dim_customer_scd2 WHERE is_current = TRUE;
-- State as of specific date
SELECT
customer_id,
customer_name,
address,
city,
state,
status
FROM dim_customer_scd2
WHERE '2026-01-15 12:00:00'::TIMESTAMP_LTZ BETWEEN effective_start_date AND effective_end_date;
-- Find all changes for a customer
SELECT
customer_id,
customer_name,
address || ', ' || city || ', ' || state as full_address,
status,
effective_start_date,
effective_end_date,
DATEDIFF(day, effective_start_date, effective_end_date) as days_active
FROM dim_customer_scd2
WHERE customer_id = 1
ORDER BY effective_start_date;
-- Customers who changed status in last 30 days
SELECT DISTINCT
current_version.customer_id,
current_version.customer_name,
previous_version.status as old_status,
current_version.status as new_status,
current_version.effective_start_date as changed_on
FROM dim_customer_scd2 current_version
JOIN dim_customer_scd2 previous_version
ON current_version.customer_id = previous_version.customer_id
AND previous_version.effective_end_date = current_version.effective_start_date
WHERE current_version.is_current = TRUE
AND current_version.status != previous_version.status
AND current_version.effective_start_date >= DATEADD(day, -30, CURRENT_TIMESTAMP());
Part 5: Real Use Case #3 – Multi-Table Pipeline
Scenario: Process orders → update customer metrics → trigger alerts
-- Source tables
CREATE OR REPLACE TABLE raw_orders (
order_id INTEGER,
customer_id INTEGER,
amount DECIMAL(10,2),
order_date DATE,
status STRING,
inserted_at TIMESTAMP_LTZ DEFAULT CURRENT_TIMESTAMP()
);
CREATE OR REPLACE TABLE customer_metrics (
customer_id INTEGER PRIMARY KEY,
total_orders INTEGER DEFAULT 0,
total_spent DECIMAL(15,2) DEFAULT 0,
avg_order_value DECIMAL(10,2) DEFAULT 0,
last_order_date DATE,
customer_segment STRING, -- 'VIP', 'Regular', 'At Risk'
updated_at TIMESTAMP_LTZ
);
CREATE OR REPLACE TABLE vip_alerts (
alert_id INTEGER AUTOINCREMENT,
customer_id INTEGER,
alert_type STRING,
message STRING,
created_at TIMESTAMP_LTZ DEFAULT CURRENT_TIMESTAMP()
);
-- Create streams
CREATE OR REPLACE STREAM raw_orders_stream ON TABLE raw_orders;
-- Task 1: Process new orders
CREATE OR REPLACE TASK process_new_orders
WAREHOUSE = etl_wh
SCHEDULE = '5 MINUTE'
WHEN SYSTEM$STREAM_HAS_DATA('raw_orders_stream')
AS
MERGE INTO customer_metrics target
USING (
SELECT
customer_id,
COUNT(*) as new_order_count,
SUM(amount) as new_order_amount,
MAX(order_date) as latest_order_date
FROM raw_orders_stream
WHERE METADATA$ACTION = 'INSERT'
AND status = 'COMPLETED'
GROUP BY customer_id
) source
ON target.customer_id = source.customer_id
WHEN MATCHED THEN UPDATE SET
total_orders = total_orders + source.new_order_count,
total_spent = total_spent + source.new_order_amount,
avg_order_value = (total_spent + source.new_order_amount) / (total_orders + source.new_order_count),
last_order_date = GREATEST(target.last_order_date, source.latest_order_date),
updated_at = CURRENT_TIMESTAMP()
WHEN NOT MATCHED THEN INSERT
(customer_id, total_orders, total_spent, avg_order_value, last_order_date, updated_at)
VALUES
(source.customer_id, source.new_order_count, source.new_order_amount,
source.new_order_amount / source.new_order_count, source.latest_order_date, CURRENT_TIMESTAMP());
-- Task 2: Update customer segments (runs after Task 1)
CREATE OR REPLACE TASK update_customer_segments
WAREHOUSE = etl_wh
AFTER process_new_orders
AS
UPDATE customer_metrics
SET
customer_segment = CASE
WHEN total_spent >= 10000 THEN 'VIP'
WHEN total_spent >= 1000 THEN 'Regular'
WHEN DATEDIFF(day, last_order_date, CURRENT_DATE()) > 180 THEN 'At Risk'
ELSE 'Regular'
END,
updated_at = CURRENT_TIMESTAMP()
WHERE updated_at >= DATEADD(minute, -10, CURRENT_TIMESTAMP()); -- Only recently updated-- Task 3: Generate VIP alerts (runs after Task 2)
CREATE OR REPLACE TASK generate_vip_alerts
WAREHOUSE = etl_wh
AFTER update_customer_segments
AS
INSERT INTO vip_alerts (customer_id, alert_type, message)
SELECT
customer_id,
'NEW_VIP' as alert_type,
'Customer ' || customer_id || ' just became VIP with $' || total_spent || ' total spent!'
FROM customer_metrics
WHERE customer_segment = 'VIP'
AND updated_at >= DATEADD(minute, -10, CURRENT_TIMESTAMP())
AND total_spent >= 10000
AND total_spent < 10500; -- Likely just crossed threshold-- Resume tasks (child first!)
ALTER TASK generate_vip_alerts RESUME;
ALTER TASK update_customer_segments RESUME;
ALTER TASK process_new_orders RESUME;
-- Test the pipeline
INSERT INTO raw_orders VALUES
(1, 101, 500.00, '2026-01-15', 'COMPLETED', CURRENT_TIMESTAMP()),
(2, 101, 9600.00, '2026-01-16', 'COMPLETED', CURRENT_TIMESTAMP()); -- Should trigger VIP!-- Wait 5-10 minutes, check results
SELECT * FROM customer_metrics WHERE customer_id = 101;
SELECT * FROM vip_alerts WHERE customer_id = 101;
Part 6: Error Handling and Monitoring
Handling Task Failures
-- Task with error handling
CREATE OR REPLACE TASK robust_processing
WAREHOUSE = etl_wh
SCHEDULE = '10 MINUTE'
AS
BEGIN
-- Use TRY-CATCH pattern
INSERT INTO processing_log VALUES ('Starting process', CURRENT_TIMESTAMP(), NULL);
BEGIN
-- Your processing logic
MERGE INTO target_table ...;
INSERT INTO processing_log VALUES ('Success', CURRENT_TIMESTAMP(), NULL);
EXCEPTION
WHEN OTHER THEN
INSERT INTO error_log VALUES (SQLERRM, CURRENT_TIMESTAMP());
RETURN;
END;
END;
Monitoring Task Execution
-- Create monitoring view
CREATE OR REPLACE VIEW task_monitoring AS
SELECT
name as task_name,
state,
schedule,
warehouse_name,
error_code,
error_message,
scheduled_time,
query_start_time,
completed_time,
DATEDIFF(second, query_start_time, completed_time) as execution_seconds
FROM TABLE(INFORMATION_SCHEMA.TASK_HISTORY(
scheduled_time_range_start => DATEADD(hour, -24, CURRENT_TIMESTAMP())
))
ORDER BY scheduled_time DESC;
-- Check for failures
SELECT *
FROM task_monitoring
WHERE state = 'FAILED'
ORDER BY scheduled_time DESC;
-- Check average execution time
SELECT
task_name,
COUNT(*) as runs,
AVG(execution_seconds) as avg_seconds,
MAX(execution_seconds) as max_seconds,
COUNT(CASE WHEN state = 'FAILED' THEN 1 END) as failure_count
FROM task_monitoring
WHERE scheduled_time >= DATEADD(day, -7, CURRENT_TIMESTAMP())
GROUP BY task_name
ORDER BY failure_count DESC, avg_seconds DESC;
Stream Lag Monitoring
-- Check if streams are falling behind
SELECT
table_name,
stream_name,
SYSTEM$STREAM_GET_TABLE_TIMESTAMP(stream_name) as stream_position,
CURRENT_TIMESTAMP() as current_time,
DATEDIFF(minute,
SYSTEM$STREAM_GET_TABLE_TIMESTAMP(stream_name),
CURRENT_TIMESTAMP()
) as lag_minutes
FROM information_schema.streams
WHERE table_schema = CURRENT_SCHEMA();
-- Alert if lag > 1 hour
SELECT
stream_name,
lag_minutes,
'WARNING: Stream falling behind!' as alert
FROM (
SELECT
stream_name,
DATEDIFF(minute,
SYSTEM$STREAM_GET_TABLE_TIMESTAMP(stream_name),
CURRENT_TIMESTAMP()
) as lag_minutes
FROM information_schema.streams
)
WHERE lag_minutes > 60;
Part 7: Performance Optimization
Tip 1: Minimize Stream Scans
-- Bad: Scanning stream multiple times
CREATE TASK inefficient_task AS
BEGIN
INSERT INTO table1 SELECT * FROM my_stream WHERE condition1;
INSERT INTO table2 SELECT * FROM my_stream WHERE condition2;
END;
-- Problem: Stream scanned twice (expensive!)-- Good: Scan once, use temp table
CREATE TASK efficient_task AS
BEGIN
CREATE TEMPORARY TABLE stream_data AS SELECT * FROM my_stream;
INSERT INTO table1 SELECT * FROM stream_data WHERE condition1;
INSERT INTO table2 SELECT * FROM stream_data WHERE condition2;
DROP TABLE stream_data;
END;
Tip 2: Use Clustering for Large Streams
-- If stream source table is large, cluster it
ALTER TABLE large_source_table CLUSTER BY (date_column);
-- Improves stream performance significantly
Tip 3: Right-Size Warehouses
-- Use smaller warehouses for simple tasks
CREATE TASK simple_aggregation
WAREHOUSE = X_SMALL_WH -- Don't waste credits
SCHEDULE = '5 MINUTE'
AS ...;
-- Use larger for complex processing
CREATE TASK complex_transformations
WAREHOUSE = LARGE_WH
SCHEDULE = '1 HOUR'
AS ...;
Tip 4: Task Scheduling Strategy
-- Stagger tasks to avoid warehouse contention
CREATE TASK task_1 SCHEDULE = 'USING CRON 0 * * * * UTC' AS ...; -- Every hour at :00
CREATE TASK task_2 SCHEDULE = 'USING CRON 15 * * *
I’ve been working with Snowflake for the past three years, and honestly, query optimization used to keep me up at night. Our monthly bills were climbing, queries were timing out, and my team was getting frustrated. If you’re reading this, you’re probably in a similar boat. Let me share what I’ve learned through trial and error, some expensive mistakes, and eventually figuring out what actually moves the needle. Why Your Queries Are Probably Slower (and More Expensive) Than They Should Be Last month, I was debugging a dashboard that was taking forever to load. The query looked fine at first glance, but it was chewing through credits like crazy. Turns out, I was making three classic mistakes that most people miss. The thing about Snowflake is that it’s incredibly powerful, but that power comes with responsibility. Unlike traditional databases where you might get away with sloppy queries, Snowflake will happily scan your entire data warehouse if you let it. The Clustering Key Strategy That Cut Our Costs by 40% Here’s a real scenario from our production environment. We had a massive events table with about 2 billion rows, and every query against it was painful.
-- Before: This was scanning almost the entire table
SELECT user_id, event_type, COUNT(*) as event_count
FROM events
WHERE event_date BETWEEN '2026-01-01' AND '2026-01-31'
GROUP BY user_id, event_type;
The query was taking 45 seconds and using a large warehouse. After adding a clustering key on event_date, the same query dropped to 8 seconds on a medium warehouse.
ALTER TABLE events CLUSTER BY (event_date);
But here’s what nobody tells you: clustering isn’t free. It costs credits to maintain, so you need to be strategic. We only cluster on columns that appear frequently in WHERE clauses and have high cardinality. For our events table, event_date made perfect sense because almost every query filtered on it. The sweet spot? Tables over 1TB that you query frequently with predictable filter patterns. Search Optimization Service: My New Secret Weapon Snowflake rolled out some improvements to their Search Optimization Service this year, and it’s been a game changer for our point lookup queries. We have a products table where users constantly search by SKU or product name. Before enabling search optimization, these queries were doing full table scans even though we had proper filters:
SELECT * FROM products WHERE sku = 'PROD-2026-XYZ-123';
After enabling it:
ALTER TABLE products ADD SEARCH OPTIMIZATION ON EQUALITY(sku, product_name);
Point lookups went from 3-4 seconds to under 200 milliseconds. The cost? About $2 per day for maintenance on a 50 million row table. Totally worth it for user-facing queries.
The Result Cache Trick That’s Often Misunderstood Everyone knows Snowflake caches results for 24 hours, but most people don’t optimize for it. I see developers constantly writing queries that can’t benefit from the cache.
Bad practice:
SELECT *, CURRENT_TIMESTAMP() as query_time
FROM sales
WHERE sale_date = CURRENT_DATE();
Every time this runs, CURRENT_TIMESTAMP() changes, so you get a cache miss. Same with CURRENT_DATE() in the WHERE clause. Better approach:
-- Run this once at the start of your ETL job
SET query_date = CURRENT_DATE();
-- Then use the variable
SELECT * FROM sales WHERE sale_date = $query_date;
This simple change increased our cache hit rate from 12% to 68% for our daily reporting jobs. Materialized Views: When They’re Worth It (And When They’re Not) I wasted a week last year building materialized views that actually made things worse. Here’s what I learned. Materialized views work great when you have expensive aggregations that get queried repeatedly, but the base data doesn’t change often. We have a customer_lifetime_value table that aggregates data from multiple sources:
CREATE MATERIALIZED VIEW customer_ltv_summary AS
SELECT
customer_id,
SUM(order_total) as total_revenue,
COUNT(DISTINCT order_id) as order_count,
AVG(order_total) as avg_order_value,
MAX(order_date) as last_order_date
FROM orders
GROUP BY customer_id;
This view gets queried hundreds of times per day, but the underlying orders table only gets new data once daily during our ETL run. Perfect use case. Bad use case? We tried materializing a view on our real-time events stream. The constant refreshing cost more than just running the queries directly.
The Warehouse Sizing Reality Check I used to think bigger warehouses were always faster. Turns out, that’s not how it works. For queries that process small amounts of data (under 100MB), an X-Small warehouse is often just as fast as an X-Large. We were using Large warehouses for everything because “we wanted it fast,” but we were just burning money.
Here’s my current rule of thumb: ∙ X-Small/Small: Point lookups, small aggregations, dev work ∙ Medium: Regular analytical queries processing under 1GB ∙ Large: Heavy aggregations, complex joins over 1GB ∙ X-Large and above: Only when you’re processing multiple terabytes or need serious parallelism
We also started using multi-cluster warehouses for our user-facing dashboards. During business hours, it auto-scales up to 3 clusters, then scales back down to 1 at night. No more queue times during peak hours, and we’re not paying for idle capacity.
Query Pruning: The Feature You’re Probably Not Leveraging Snowflake’s automatic query pruning is amazing when you structure your data correctly. We partition our fact tables by date and use it consistently in WHERE clauses. This query scans maybe 1% of the table:
SELECT customer_id, SUM(amount)
FROM transactions
WHERE transaction_date BETWEEN '2026-01-01' AND '2026-01-07'
GROUP BY customer_id;
You can check how much pruning is happening with:
SELECT * FROM TABLE(INFORMATION_SCHEMA.QUERY_HISTORY())
WHERE query_id = 'your_query_id';
Look at the PARTITIONS_SCANNED vs PARTITIONS_TOTAL ratio. If you’re scanning more than 20% of partitions regularly, your data structure needs work. The JOIN Order Mistake Costing You Time Snowflake’s optimizer is smart, but you can still help it. When joining tables, I always put the largest table first and use explicit join conditions. Inefficient:
SELECT *
FROM small_table s, huge_table h, medium_table m
WHERE s.id = h.small_id
AND h.id = m.huge_id;
Better:
SELECT *
FROM huge_table h
INNER JOIN medium_table m ON h.id = m.huge_id
INNER JOIN small_table s ON h.small_id = s.id;
Also, I always use INNER JOIN instead of comma-separated FROM clauses. It’s clearer and gives the optimizer better information. Monitoring That Actually Helps Every week, I run this query to find our most expensive operations:
SELECT
query_type,
warehouse_name,
user_name,
AVG(execution_time/1000) as avg_seconds,
SUM(credits_used_cloud_services) as total_credits,
COUNT(*) as query_count
FROM SNOWFLAKE.ACCOUNT_USAGE.QUERY_HISTORY
WHERE start_time >= DATEADD(day, -7, CURRENT_TIMESTAMP())
AND execution_status = 'SUCCESS'
GROUP BY 1,2,3
HAVING total_credits > 1
ORDER BY total_credits DESC
LIMIT 20;
This shows me exactly where credits are going and which users or processes need optimization attention.
What’s Actually Working for Us Right Now After months of optimization, here’s what made the biggest difference:
1. We reduced our warehouse usage by 45% just by right-sizing and using auto-suspend aggressively (1 minute timeout for dev, 5 minutes for production).
2. Clustering our largest tables on date columns cut query times in half for 80% of our analytics workload.
3. Moving to task-based scheduling instead of always-on warehouses saved us about $3000 monthly.
4. Teaching our analysts to use LIMIT during development seems obvious, but it made a huge difference in reducing waste.
The Bottom Line Query optimization in Snowflake isn’t about one magic trick. It’s about understanding your workload, monitoring what’s actually happening, and making incremental improvements.
Start with the low-hanging fruit: right-size your warehouses, add clustering to your biggest tables, and make sure your queries can leverage the result cache. Then move on to more advanced techniques like search optimization and materialized views for specific use cases.
You know that feeling when someone asks “What did we decide about the API redesign?” and you’re frantically scrolling through three weeks of meeting notes trying to find that one conversation?
Or when your manager asks “What action items were assigned to the engineering team last month?” and you realize those decisions are buried across 47 different meeting transcripts scattered in Google Docs, Notion, and email threads?
Yeah, we’ve all been there.
Here’s the thing: companies have meetings. Lots of them. And every single meeting contains valuable information—decisions made, problems discussed, action items assigned, ideas shared. But all that knowledge just… disappears into the void of meeting notes that nobody reads again.
Until now.
What if we could build a system where you just ask “What did we decide about the database migration?” and get an instant answer with exact sources? Not some generic corporate search that returns 500 irrelevant documents, but an actual intelligent assistant that understands context.
That’s exactly what we can build with Snowflake Cortex. And honestly? It’s simpler than you think.
What We’re Building (In Plain English)
Before diving into code, let’s understand what a Meeting Notes RAG actually does:
Convert them into a format that AI can search semantically (not just keyword matching)
When someone asks a question, find the most relevant meeting notes
Use an AI model to generate an intelligent answer based on those notes
Show sources so people can verify information
Real example:
Question: “Why did we choose PostgreSQL over MySQL?”
System finds: Engineering meeting from March 15th discussing database options
Answer: “According to the March 15th engineering meeting, the team chose PostgreSQL primarily because of better JSON support and more robust handling of concurrent writes. Sarah from backend also mentioned PostgreSQL’s superior full-text search capabilities.”
See? Not just “here are 50 documents mentioning PostgreSQL” but an actual synthesized answer with context.
Why Snowflake for This?
You might be thinking: “Can’t I just use ChatGPT with my notes?”
Sure, but here’s why Snowflake is better for this:
Security: Meeting notes contain sensitive information. With Snowflake, data never leaves your secure environment
Scale: Got 10,000 meetings? No problem. Snowflake handles it easily
Integration: Your meeting data might already be in Snowflake, or easily pipeable
Cortex Search: Built-in vector search—no need for external vector databases
SQL interface: Everyone on your team can query it without learning new tools
Cost: Pay only for what you use, no separate infrastructure
Plus, there’s something elegant about keeping everything in one place.
The Architecture (Keep It Simple)
Here’s how we can structure this:
Meeting Notes (Zoom, Teams, Google Meet transcripts)
↓
Load into Snowflake table
↓
Split into chunks
↓
Generate vector embeddings
↓
Create Cortex Search Service
↓
User asks question → Find relevant chunks → Generate answer with sources
No microservices, no Kubernetes, no headaches. Just Snowflake doing what it does best.
Step 1: Setting Up the Foundation
First, let’s create a proper database structure. We’re organizing this so it’s maintainable and scalable.
-- Create dedicated database for meeting intelligence
CREATE DATABASE IF NOT EXISTS meeting_intelligence;
USE DATABASE meeting_intelligence;
-- Create schema for organization
CREATE SCHEMA IF NOT EXISTS meetings;
USE SCHEMA meetings;
-- Set up compute
CREATE WAREHOUSE IF NOT EXISTS meeting_rag_wh
WITH
WAREHOUSE_SIZE = 'SMALL'
AUTO_SUSPEND = 60
AUTO_RESUME = TRUE
INITIALLY_SUSPENDED = TRUE;
USE WAREHOUSE meeting_rag_wh;
-- Ensure we have Cortex access
-- (Account admin needs to grant this)
-- GRANT DATABASE ROLE SNOWFLAKE.CORTEX_USER TO ROLE your_role_name;
Nothing fancy here—just clean organization. A SMALL warehouse is perfectly fine for this; we can always scale if needed.
Step 2: Designing the Meeting Notes Table
This is where thoughtful schema design matters. We want to capture not just the content, but useful metadata.
-- Main table for meeting transcripts
CREATE OR REPLACE TABLE meeting_transcripts (
meeting_id STRING PRIMARY KEY,
meeting_title STRING NOT NULL,
meeting_date TIMESTAMP_LTZ NOT NULL,
meeting_type STRING, -- 'standup', 'planning', 'retrospective', 'one-on-one'
attendees ARRAY,
duration_minutes INTEGER,
transcript_text STRING NOT NULL,
action_items ARRAY,
decisions_made ARRAY,
topics_discussed ARRAY,
recording_url STRING,
created_at TIMESTAMP_LTZ DEFAULT CURRENT_TIMESTAMP(),
updated_at TIMESTAMP_LTZ DEFAULT CURRENT_TIMESTAMP()
);
-- Add some realistic sample data
INSERT INTO meeting_transcripts VALUES
(
'MTG-2024-001',
'Q1 Product Planning',
'2024-01-15 10:00:00',
'planning',
ARRAY_CONSTRUCT('Sarah Chen', 'Mike Rodriguez', 'Emily Watson', 'David Park'),
60,
'Sarah opened the meeting discussing Q1 priorities. The main focus is launching the new dashboard feature by end of February. Mike raised concerns about the API rate limiting affecting customer experience. After discussion, the team decided to implement a caching layer using Redis before launch. Emily suggested we should also add analytics to track dashboard load times. David mentioned the infrastructure team can provision the Redis cluster within a week. Action items: Mike to create Redis implementation plan, Emily to design analytics dashboard, David to provision infrastructure by Jan 22.',
ARRAY_CONSTRUCT(
'Mike: Create Redis implementation plan by Jan 18',
'Emily: Design analytics dashboard mockup by Jan 20',
'David: Provision Redis cluster by Jan 22'
),
ARRAY_CONSTRUCT(
'Implement Redis caching layer before dashboard launch',
'Add analytics tracking for dashboard performance',
'Q1 launch date confirmed for Feb 28'
),
ARRAY_CONSTRUCT('Dashboard launch', 'API performance', 'Redis caching', 'Analytics'),
'https://zoom.us/rec/share/mock-url-001',
CURRENT_TIMESTAMP(),
CURRENT_TIMESTAMP()
),
(
'MTG-2024-002',
'Database Migration Discussion',
'2024-01-22 14:00:00',
'technical',
ARRAY_CONSTRUCT('Tom Liu', 'Sarah Chen', 'Alex Kumar'),
45,
'Tom presented three options for the database migration: PostgreSQL, MySQL, and staying with current setup. Sarah advocated strongly for PostgreSQL citing better JSON support and more robust concurrent write handling. Alex agreed, mentioning PostgreSQL full-text search capabilities would be beneficial for the search feature we are planning. The team also discussed migration timeline - estimated 3 weeks for full migration including testing. Concern raised about downtime, but Tom confirmed we can do blue-green deployment with minimal disruption. Decision: Move forward with PostgreSQL, start migration planning next week.',
ARRAY_CONSTRUCT(
'Tom: Create detailed migration plan by Jan 29',
'Sarah: Review PostgreSQL best practices documentation',
'Alex: Set up staging PostgreSQL environment by Feb 1'
),
ARRAY_CONSTRUCT(
'Selected PostgreSQL as new database',
'Migration timeline: 3 weeks',
'Use blue-green deployment strategy'
),
ARRAY_CONSTRUCT('Database migration', 'PostgreSQL', 'Blue-green deployment'),
'https://zoom.us/rec/share/mock-url-002',
CURRENT_TIMESTAMP(),
CURRENT_TIMESTAMP()
),
(
'MTG-2024-003',
'API Security Review',
'2024-02-05 11:00:00',
'security',
ARRAY_CONSTRUCT('Jennifer Lee', 'Tom Liu', 'Mike Rodriguez'),
90,
'Jennifer led security audit of our API endpoints. Critical finding: several endpoints lack proper rate limiting, making them vulnerable to DDoS attacks. Mike explained current authentication uses JWT but token expiry is set too long at 7 days. Team agreed to reduce to 24 hours and implement refresh token mechanism. Jennifer recommended adding API key rotation policy every 90 days. Also discussed implementing request signing for sensitive endpoints. Tom mentioned we should add monitoring alerts for unusual API patterns. Decision: Implement all recommendations before March 1st launch. This is now a blocker for product launch.',
ARRAY_CONSTRUCT(
'Mike: Implement rate limiting on all API endpoints by Feb 12',
'Tom: Set up monitoring and alerts by Feb 15',
'Jennifer: Document API key rotation policy by Feb 10',
'Mike: Reduce JWT expiry to 24h and add refresh tokens by Feb 16'
),
ARRAY_CONSTRUCT(
'All API security improvements are launch blockers',
'JWT token expiry reduced from 7 days to 24 hours',
'Implement 90-day API key rotation policy',
'Add request signing for sensitive endpoints'
),
ARRAY_CONSTRUCT('API security', 'Rate limiting', 'JWT tokens', 'Authentication'),
'https://zoom.us/rec/share/mock-url-003',
CURRENT_TIMESTAMP(),
CURRENT_TIMESTAMP()
),
(
'MTG-2024-004',
'Weekly Engineering Standup',
'2024-02-12 09:00:00',
'standup',
ARRAY_CONSTRUCT('Sarah Chen', 'Mike Rodriguez', 'Emily Watson', 'David Park', 'Tom Liu'),
30,
'Quick updates from everyone. Sarah completed the dashboard analytics implementation, looking good in staging. Mike finished API rate limiting yesterday, currently doing load testing. Emily working on mobile responsive design, encountered some CSS issues with the new dashboard on tablets. David reports Redis cluster is stable, handling 10k requests per second easily. Tom mentioned database migration testing is going well, planning cutover for next weekend. No blockers reported. Brief discussion about whether we need additional caching for mobile API endpoints - agreed to monitor after launch and optimize if needed.',
ARRAY_CONSTRUCT(
'Emily: Fix tablet responsive issues by Feb 14',
'Mike: Complete load testing report by Feb 13',
'Tom: Finalize migration cutover plan by Feb 14'
),
ARRAY_CONSTRUCT(),
ARRAY_CONSTRUCT('Sprint progress', 'Dashboard status', 'Mobile responsive', 'Database migration'),
'https://zoom.us/rec/share/mock-url-004',
CURRENT_TIMESTAMP(),
CURRENT_TIMESTAMP()
),
(
'MTG-2024-005',
'Customer Feedback Review',
'2024-02-20 15:00:00',
'product',
ARRAY_CONSTRUCT('Emily Watson', 'Sarah Chen', 'Product Manager Jane Smith'),
60,
'Jane presented findings from customer interviews conducted last week. Top request: ability to export dashboard data to Excel. 15 out of 20 customers mentioned this. Also strong demand for custom date range filters, currently we only support preset ranges. Sarah noted export feature is technically straightforward, could be done in one sprint. Emily suggested we should also add PDF export option. Jane agreed, mentioned several enterprise customers specifically asked for PDF reports for presentations. Team consensus: prioritize Excel export for Q2, PDF can be Q3. Also discussed adding keyboard shortcuts for power users - Emily volunteered to research what shortcuts would be most useful.',
ARRAY_CONSTRUCT(
'Sarah: Create technical spec for Excel export by Feb 27',
'Emily: Research and propose keyboard shortcuts by Feb 29',
'Jane: Follow up with customers about custom date ranges by Mar 1'
),
ARRAY_CONSTRUCT(
'Excel export prioritized for Q2 Sprint 1',
'PDF export moved to Q3',
'Custom date range filters to be designed',
'Keyboard shortcuts under consideration'
),
ARRAY_CONSTRUCT('Customer feedback', 'Feature requests', 'Excel export', 'Dashboard improvements'),
'https://zoom.us/rec/share/mock-url-005',
CURRENT_TIMESTAMP(),
CURRENT_TIMESTAMP()
);
-- Verify data loaded
SELECT
meeting_id,
meeting_title,
meeting_date,
ARRAY_SIZE(attendees) as attendee_count,
ARRAY_SIZE(action_items) as action_count,
LEFT(transcript_text, 100) || '...' as preview
FROM meeting_transcripts
ORDER BY meeting_date;
Notice how we’re capturing structured data (action items, decisions, topics) alongside unstructured text. This dual approach gives us flexibility in how we search and analyze later.
Step 3: Chunking Strategy for Meetings
Unlike documentation, meetings have natural structure—they flow chronologically. We can chunk intelligently based on topics or time segments.
-- Table for meeting chunks (optimized for retrieval)
CREATE OR REPLACE TABLE meeting_chunks (
chunk_id STRING PRIMARY KEY,
meeting_id STRING,
chunk_index INTEGER,
chunk_text STRING,
chunk_size INTEGER,
chunk_metadata VARIANT,
chunk_embedding VECTOR(FLOAT, 1024)
);
-- Use SPLIT_TEXT_RECURSIVE_CHARACTER for intelligent chunking
-- This function preserves sentence boundaries and context
INSERT INTO meeting_chunks (chunk_id, meeting_id, chunk_index, chunk_text, chunk_size, chunk_metadata)
SELECT
meeting_id || '_chunk_' || chunk_index as chunk_id,
meeting_id,
chunk_index,
chunk_text,
LENGTH(chunk_text) as chunk_size,
OBJECT_CONSTRUCT(
'meeting_title', meeting_title,
'meeting_date', meeting_date,
'meeting_type', meeting_type,
'attendees', attendees,
'duration_minutes', duration_minutes,
'has_action_items', ARRAY_SIZE(action_items) > 0,
'has_decisions', ARRAY_SIZE(decisions_made) > 0,
'topics', topics_discussed,
'total_chunks', total_chunks_in_meeting
) as chunk_metadata
FROM (
SELECT
mt.meeting_id,
mt.meeting_title,
mt.meeting_date,
mt.meeting_type,
mt.attendees,
mt.duration_minutes,
mt.action_items,
mt.decisions_made,
mt.topics_discussed,
chunk.value::STRING as chunk_text,
chunk.index as chunk_index,
ARRAY_SIZE(chunks_array) as total_chunks_in_meeting
FROM meeting_transcripts mt,
LATERAL (
-- SPLIT_TEXT_RECURSIVE_CHARACTER parameters:
-- text: the content to split
-- max_characters: target size per chunk (500-1000 works well)
SELECT SNOWFLAKE.CORTEX.SPLIT_TEXT_RECURSIVE_CHARACTER(
mt.transcript_text,
500 -- Target 500 characters per chunk
) as chunks_array
) split_result,
LATERAL FLATTEN(input => chunks_array) chunk
);
-- Verify what we created
SELECT
meeting_id,
chunk_metadata:meeting_title::STRING as meeting_title,
COUNT(*) as num_chunks,
AVG(chunk_size) as avg_chunk_size,
MIN(chunk_size) as min_chunk_size,
MAX(chunk_size) as max_chunk_size
FROM meeting_chunks
GROUP BY meeting_id, chunk_metadata:meeting_title::STRING
ORDER BY chunk_metadata:meeting_date::TIMESTAMP_LTZ;
-- View actual chunks for one meeting
SELECT
chunk_id,
chunk_index,
chunk_size,
LEFT(chunk_text, 150) || '...' as chunk_preview
FROM meeting_chunks
WHERE meeting_id = 'MTG-2024-002' -- Database Migration Discussion
ORDER BY chunk_index;
-- ========================================
-- ADAPTIVE CHUNKING (Optional Enhancement)
-- ========================================
-- Adjust chunk size based on meeting duration
TRUNCATE TABLE meeting_chunks;
INSERT INTO meeting_chunks (chunk_id, meeting_id, chunk_index, chunk_text, chunk_size, chunk_metadata)
SELECT
meeting_id || '_chunk_' || chunk_index as chunk_id,
meeting_id,
chunk_index,
chunk_text,
LENGTH(chunk_text) as chunk_size,
chunk_metadata
FROM (
SELECT
mt.meeting_id,
chunk.value::STRING as chunk_text,
chunk.index as chunk_index,
OBJECT_CONSTRUCT(
'meeting_title', mt.meeting_title,
'meeting_date', mt.meeting_date,
'meeting_type', mt.meeting_type,
'attendees', mt.attendees,
'duration_minutes', mt.duration_minutes,
'has_action_items', ARRAY_SIZE(mt.action_items) > 0,
'has_decisions', ARRAY_SIZE(mt.decisions_made) > 0,
'topics', mt.topics_discussed
) as chunk_metadata
FROM meeting_transcripts mt,
LATERAL (
SELECT SNOWFLAKE.CORTEX.SPLIT_TEXT_RECURSIVE_CHARACTER(
mt.transcript_text,
CASE
-- Short meetings: larger chunks
WHEN mt.duration_minutes <= 30 THEN 800
-- Medium meetings: standard chunks
WHEN mt.duration_minutes <= 60 THEN 500
-- Long meetings: smaller chunks for precision
ELSE 400
END
) as chunks_array
) split_result,
LATERAL FLATTEN(input => chunks_array) chunk
);
-- ========================================
-- ENHANCED CHUNKING PROCEDURE (Production)
-- ========================================
-- This creates separate chunks for actions and decisions
CREATE OR REPLACE PROCEDURE chunk_meeting_intelligently(p_meeting_id STRING)
RETURNS STRING
LANGUAGE SQL
AS
$$
BEGIN
-- First, chunk the main transcript
INSERT INTO meeting_chunks (chunk_id, meeting_id, chunk_index, chunk_text, chunk_size, chunk_metadata)
SELECT
p_meeting_id || '_main_' || chunk.index as chunk_id,
p_meeting_id as meeting_id,
chunk.index as chunk_index,
chunk.value::STRING as chunk_text,
LENGTH(chunk.value::STRING) as chunk_size,
OBJECT_CONSTRUCT(
'meeting_title', mt.meeting_title,
'meeting_date', mt.meeting_date,
'meeting_type', mt.meeting_type,
'chunk_type', 'transcript',
'attendees', mt.attendees
) as chunk_metadata
FROM meeting_transcripts mt,
LATERAL (
SELECT SNOWFLAKE.CORTEX.SPLIT_TEXT_RECURSIVE_CHARACTER(
mt.transcript_text,
500
) as chunks_array
) split_result,
LATERAL FLATTEN(input => chunks_array) chunk
WHERE mt.meeting_id = p_meeting_id;
-- Add action items as dedicated chunks
INSERT INTO meeting_chunks (chunk_id, meeting_id, chunk_index, chunk_text, chunk_size, chunk_metadata)
SELECT
p_meeting_id || '_action_' || action.index as chunk_id,
p_meeting_id as meeting_id,
1000 + action.index as chunk_index,
'ACTION ITEM: ' || action.value::STRING as chunk_text,
LENGTH(action.value::STRING) as chunk_size,
OBJECT_CONSTRUCT(
'meeting_title', mt.meeting_title,
'meeting_date', mt.meeting_date,
'chunk_type', 'action_item',
'attendees', mt.attendees
) as chunk_metadata
FROM meeting_transcripts mt,
LATERAL FLATTEN(input => mt.action_items) action
WHERE mt.meeting_id = p_meeting_id
AND ARRAY_SIZE(mt.action_items) > 0;
-- Add decisions as dedicated chunks
INSERT INTO meeting_chunks (chunk_id, meeting_id, chunk_index, chunk_text, chunk_size, chunk_metadata)
SELECT
p_meeting_id || '_decision_' || decision.index as chunk_id,
p_meeting_id as meeting_id,
2000 + decision.index as chunk_index,
'DECISION MADE: ' || decision.value::STRING as chunk_text,
LENGTH(decision.value::STRING) as chunk_size,
OBJECT_CONSTRUCT(
'meeting_title', mt.meeting_title,
'meeting_date', mt.meeting_date,
'chunk_type', 'decision',
'attendees', mt.attendees
) as chunk_metadata
FROM meeting_transcripts mt,
LATERAL FLATTEN(input => mt.decisions_made) decision
WHERE mt.meeting_id = p_meeting_id
AND ARRAY_SIZE(mt.decisions_made) > 0;
RETURN 'Successfully chunked meeting ' || p_meeting_id;
END;
$$;
-- Test the enhanced chunking
CALL chunk_meeting_intelligently('MTG-2024-001');
-- View results by chunk type
SELECT
chunk_id,
chunk_metadata:chunk_type::STRING as type,
chunk_size,
LEFT(chunk_text, 100) || '...' as preview
FROM meeting_chunks
WHERE meeting_id = 'MTG-2024-001'
ORDER BY chunk_index;
-- ========================================
-- QUALITY VALIDATION
-- ========================================
-- Check chunk quality distribution
WITH chunk_stats AS (
SELECT
meeting_id,
chunk_metadata:meeting_title::STRING as meeting_title,
COUNT(*) as total_chunks,
AVG(chunk_size) as avg_size,
STDDEV(chunk_size) as size_variation,
COUNT(CASE WHEN chunk_size < 200 THEN 1 END) as too_small_count,
COUNT(CASE WHEN chunk_size > 1000 THEN 1 END) as too_large_count
FROM meeting_chunks
GROUP BY meeting_id, meeting_title
)
SELECT
meeting_title,
total_chunks,
ROUND(avg_size, 0) as avg_chunk_size,
ROUND(size_variation, 0) as size_std_dev,
too_small_count,
too_large_count,
CASE
WHEN too_small_count > total_chunks * 0.2 THEN '⚠️ Too many small chunks'
WHEN too_large_count > total_chunks * 0.2 THEN '⚠️ Too many large chunks'
ELSE '✅ Good distribution'
END as quality_status
FROM chunk_stats
ORDER BY meeting_id;
For production systems, we might want to split longer meetings into smaller chunks—maybe 3-5 minute segments or topic-based splits. But for this example, keeping each meeting as one chunk works well since our sample meetings are relatively short.
This is where the magic starts. We’re converting text into mathematical vectors that capture semantic meaning.
-- Generate embeddings using Snowflake Cortex
UPDATE meeting_chunks
SET chunk_embedding = SNOWFLAKE.CORTEX.EMBED_TEXT_1024(
'snowflake-arctic-embed-l',
chunk_text
);
-- Verify embeddings were created
SELECT
chunk_id,
chunk_metadata:meeting_title::STRING as meeting,
chunk_embedding IS NOT NULL as has_embedding,
-- Self-similarity should be 0 (or very close)
VECTOR_L2_DISTANCE(chunk_embedding, chunk_embedding) as self_similarity
FROM meeting_chunks
LIMIT 5;
The snowflake-arctic-embed-l model creates 1024-dimensional vectors. These vectors position similar concepts close together in mathematical space—so “API security” and “authentication” end up near each other, even without sharing exact words.
Now we set up the search infrastructure. This is what makes semantic search possible.
-- Create Cortex Search Service for meeting notes
CREATE OR REPLACE CORTEX SEARCH SERVICE meeting_search_service
ON chunk_text
WAREHOUSE = meeting_rag_wh
TARGET_LAG = '1 minute'
AS (
SELECT
chunk_id,
chunk_text,
chunk_metadata,
chunk_embedding
FROM meeting_chunks
);
-- Check service status (takes a minute to initialize)
SHOW CORTEX SEARCH SERVICES;
-- Test basic search
SELECT *
FROM TABLE(
meeting_search_service!SEARCH(
QUERY => 'database migration',
LIMIT => 3
)
);
The TARGET_LAG of 1 minute means new meetings get indexed within a minute. For most use cases, this is plenty fast.
Step 6: Building the Query Interface
Now for the exciting part—creating a function that actually answers questions intelligently.
-- Create the main RAG function
CREATE OR REPLACE FUNCTION ask_meeting_assistant(question STRING)
RETURNS VARIANT
LANGUAGE SQL
AS
$$
WITH relevant_meetings AS (
-- Step 1: Find most relevant meeting chunks
SELECT
chunk_text,
chunk_metadata:meeting_title::STRING as meeting_title,
chunk_metadata:meeting_date::TIMESTAMP_LTZ as meeting_date,
chunk_metadata:attendees as attendees
FROM TABLE(
meeting_search_service!SEARCH(
QUERY => question,
LIMIT => 3
)
)
),
context_builder AS (
-- Step 2: Build context from retrieved meetings
SELECT
LISTAGG(
'Meeting: ' || meeting_title ||
'\nDate: ' || TO_VARCHAR(meeting_date, 'YYYY-MM-DD') ||
'\nAttendees: ' || ARRAY_TO_STRING(attendees, ', ') ||
'\nContent: ' || chunk_text,
'\n\n---\n\n'
) as combined_context,
ARRAY_AGG(
OBJECT_CONSTRUCT(
'title', meeting_title,
'date', meeting_date,
'attendees', attendees
)
) as sources
FROM relevant_meetings
)
-- Step 3: Generate intelligent answer
SELECT OBJECT_CONSTRUCT(
'answer', SNOWFLAKE.CORTEX.COMPLETE(
'llama3.1-70b',
'You are a helpful meeting assistant. Answer the user\'s question based ONLY on the provided meeting notes.
If the information is not in the meeting notes, say so clearly. Always mention which meeting(s) you are referencing and include relevant dates.
If there are action items or decisions related to the question, highlight them.
Meeting Notes:
' || combined_context || '
User Question: ' || question || '
Provide a clear, accurate answer with specific references to meetings and dates:'
),
'sources', sources,
'timestamp', CURRENT_TIMESTAMP()
) as result
FROM context_builder
$$;
-- Test it out!
SELECT ask_meeting_assistant('Why did we choose PostgreSQL?');
-- Parse the result nicely
SELECT
result:answer::STRING as answer,
result:sources as source_meetings,
result:timestamp::TIMESTAMP_LTZ as answered_at
FROM (
SELECT ask_meeting_assistant('Why did we choose PostgreSQL?') as result
);
Let’s break down what this function does:
Searches for the 3 most relevant meeting chunks semantically
Builds context by combining those meetings with metadata
Generates answer using an LLM that has been given specific instructions
Returns structured output with answer + sources
The key is that the LLM only uses information from our meetings—it doesn’t make things up or use its general knowledge.
Step 7: Real-World Testing
Let’s ask questions that we’d actually ask in real life:
-- Question 1: Specific decision
SELECT
result:answer::STRING as answer
FROM (
SELECT ask_meeting_assistant('Why did we choose PostgreSQL over MySQL?') as result
);
-- Question 2: Action items
SELECT
result:answer::STRING as answer
FROM (
SELECT ask_meeting_assistant('What are Mike\'s pending action items?') as result
);
-- Question 3: Timeline question
SELECT
result:answer::STRING as answer
FROM (
SELECT ask_meeting_assistant('When is the dashboard launch scheduled?') as result
);
-- Question 4: Security discussion
SELECT
result:answer::STRING as answer
FROM (
SELECT ask_meeting_assistant('What security concerns were raised about our API?') as result
);
-- Question 5: Testing boundaries
SELECT
result:answer::STRING as answer
FROM (
SELECT ask_meeting_assistant('What is the weather forecast for tomorrow?') as result
);
-- This should correctly say "not in meeting notes"
What’s impressive is how the system can connect information across multiple meetings. If you ask “What’s blocking the product launch?”, it can pull from the security meeting AND the planning meeting to give a complete answer.
Step 8: Adding Specialized Query Functions
Different people need different things from meeting notes. Let’s create targeted functions:
-- Function 1: Find action items for a person
CREATE OR REPLACE FUNCTION get_action_items_for(person_name STRING)
RETURNS TABLE (
meeting_title STRING,
meeting_date TIMESTAMP_LTZ,
action_item STRING
)
AS
$$
SELECT
meeting_title,
meeting_date,
action.value::STRING as action_item
FROM meeting_transcripts,
LATERAL FLATTEN(input => action_items) action
WHERE action.value::STRING ILIKE '%' || person_name || '%'
ORDER BY meeting_date DESC
$$;
-- Usage
SELECT * FROM TABLE(get_action_items_for('Mike'));
-- Function 2: Find all decisions in a date range
CREATE OR REPLACE FUNCTION get_decisions_between(
start_date TIMESTAMP_LTZ,
end_date TIMESTAMP_LTZ
)
RETURNS TABLE (
meeting_title STRING,
meeting_date TIMESTAMP_LTZ,
decision STRING
)
AS
$$
SELECT
meeting_title,
meeting_date,
decision.value::STRING as decision
FROM meeting_transcripts,
LATERAL FLATTEN(input => decisions_made) decision
WHERE meeting_date BETWEEN start_date AND end_date
ORDER BY meeting_date DESC
$$;
-- Usage
SELECT * FROM TABLE(get_decisions_between(
'2024-01-01'::TIMESTAMP_LTZ,
'2024-02-28'::TIMESTAMP_LTZ
));
-- Function 3: Search meetings by topic
CREATE OR REPLACE FUNCTION find_meetings_about(topic STRING)
RETURNS TABLE (
meeting_id STRING,
meeting_title STRING,
meeting_date TIMESTAMP_LTZ,
relevance_score FLOAT
)
AS
$$
SELECT
chunk_id as meeting_id,
chunk_metadata:meeting_title::STRING as meeting_title,
chunk_metadata:meeting_date::TIMESTAMP_LTZ as meeting_date,
1.0 as relevance_score -- Cortex Search returns results sorted by relevance
FROM TABLE(
meeting_search_service!SEARCH(
QUERY => topic,
LIMIT => 10
)
)
$$;
-- Usage
SELECT * FROM TABLE(find_meetings_about('API security'));
These specialized functions give your team multiple ways to interact with meeting data—some people want natural language, others want structured queries.
Step 9: Building a Conversation History Table
To make this truly useful, we should track what people ask and whether answers were helpful:
-- Track queries and feedback
CREATE OR REPLACE TABLE meeting_assistant_logs (
log_id INTEGER AUTOINCREMENT,
user_name STRING,
question STRING,
answer VARIANT,
sources_used ARRAY,
helpful_vote INTEGER, -- 1 = helpful, -1 = not helpful, NULL = no vote yet
feedback_comment STRING,
queried_at TIMESTAMP_LTZ DEFAULT CURRENT_TIMESTAMP()
);
-- Enhanced function that logs queries
CREATE OR REPLACE PROCEDURE ask_and_log(
user_name STRING,
question STRING
)
RETURNS VARIANT
LANGUAGE SQL
AS
$$
DECLARE
result VARIANT;
BEGIN
-- Get answer
result := ask_meeting_assistant(:question);
-- Log the interaction
INSERT INTO meeting_assistant_logs (user_name, question, answer, sources_used)
SELECT
:user_name,
:question,
:result,
:result:sources
;
RETURN result;
END;
$$;
-- Usage
CALL ask_and_log('[email protected]', 'What did we decide about caching?');
-- View query history
SELECT
log_id,
user_name,
question,
answer:answer::STRING as answer_preview,
helpful_vote,
queried_at
FROM meeting_assistant_logs
ORDER BY queried_at DESC
LIMIT 10;
-- Add feedback
UPDATE meeting_assistant_logs
SET helpful_vote = 1,
feedback_comment = 'Perfect! Found exactly what I needed.'
WHERE log_id = 1;
This logging is crucial for two reasons:
Accountability: Know who’s using the system and what they’re asking
Improvement: See which queries return unhelpful answers and refine
Step 10: Analytics Dashboard Queries
Let’s create queries that help us understand usage patterns:
-- Most common topics people ask about
SELECT
-- Extract key nouns/topics from questions
LOWER(REGEXP_SUBSTR(question, '\\b(database|API|security|migration|dashboard|launch|PostgreSQL|Redis|cache|decision|action)\\b', 1, 1, 'i')) as topic,
COUNT(*) as question_count
FROM meeting_assistant_logs
WHERE topic IS NOT NULL
GROUP BY topic
ORDER BY question_count DESC
LIMIT 10;
-- User engagement metrics
SELECT
user_name,
COUNT(*) as total_queries,
AVG(CASE WHEN helpful_vote = 1 THEN 1.0 ELSE 0.0 END) as satisfaction_rate,
COUNT(CASE WHEN helpful_vote = -1 THEN 1 END) as unhelpful_answers
FROM meeting_assistant_logs
GROUP BY user_name
ORDER BY total_queries DESC;
-- Meetings that get referenced most
SELECT
source.value:title::STRING as meeting_title,
source.value:date::TIMESTAMP_LTZ as meeting_date,
COUNT(*) as times_referenced
FROM meeting_assistant_logs,
LATERAL FLATTEN(input => sources_used) source
GROUP BY meeting_title, meeting_date
ORDER BY times_referenced DESC
LIMIT 10;
-- Questions that received negative feedback
SELECT
question,
answer:answer::STRING as answer,
feedback_comment,
queried_at
FROM meeting_assistant_logs
WHERE helpful_vote = -1
ORDER BY queried_at DESC;
These analytics tell us what’s working and what needs improvement. If certain types of questions consistently get negative feedback, we know where to focus our refinement efforts.
Step 11: Automating Meeting Ingestion
In production, we’d want new meetings to automatically flow into the system. Here’s how that might look:
-- Create stage for incoming meeting transcripts
CREATE OR REPLACE STAGE meeting_uploads
FILE_FORMAT = (TYPE = 'JSON');
-- Create stream to detect new meetings
CREATE OR REPLACE STREAM new_meetings_stream
ON TABLE meeting_transcripts;
-- Task to process new meetings
CREATE OR REPLACE TASK process_new_meetings
WAREHOUSE = meeting_rag_wh
SCHEDULE = '5 MINUTE'
WHEN SYSTEM$STREAM_HAS_DATA('new_meetings_stream')
AS
BEGIN
-- Insert chunks for new meetings
INSERT INTO meeting_chunks (chunk_id, meeting_id, chunk_index, chunk_text, chunk_metadata)
SELECT
meeting_id || '_' || chunk_index as chunk_id,
meeting_id,
chunk_index,
chunk_text,
chunk_metadata
FROM (
SELECT
meeting_id,
transcript_text as chunk_text,
1 as chunk_index,
OBJECT_CONSTRUCT(
'meeting_title', meeting_title,
'meeting_date', meeting_date,
'meeting_type', meeting_type,
'attendees', attendees,
'has_action_items', ARRAY_SIZE(action_items) > 0,
'has_decisions', ARRAY_SIZE(decisions_made) > 0
) as chunk_metadata
FROM new_meetings_stream
WHERE METADATA$ACTION = 'INSERT'
);
-- Generate embeddings for new chunks
UPDATE meeting_chunks
SET chunk_embedding = SNOWFLAKE.CORTEX.EMBED_TEXT_1024(
'snowflake-arctic-embed-l',
chunk_text
)
WHERE chunk_embedding IS NULL;
END;
-- Resume task
ALTER TASK process_new_meetings RESUME;
Now whenever a new meeting gets added to the meeting_transcripts table, it’s automatically chunked, embedded, and searchable within 5 minutes. No manual intervention needed.
Advanced Feature: Topic Extraction
We can use Cortex to automatically extract topics from meetings:
-- Add topics column
ALTER TABLE meeting_transcripts
ADD COLUMN ai_extracted_topics ARRAY;
-- Extract topics using LLM
UPDATE meeting_transcripts
SET ai_extracted_topics = PARSE_JSON(
SNOWFLAKE.CORTEX.COMPLETE(
'llama3.1-70b',
'Extract 3-5 main topics from this meeting transcript. Return ONLY a JSON array of strings, nothing else.
Transcript: ' || transcript_text || '
Format: ["topic1", "topic2", "topic3"]'
)
);
-- View extracted topics
SELECT
meeting_title,
meeting_date,
ai_extracted_topics
FROM meeting_transcripts
ORDER BY meeting_date;
-- Find meetings by AI-extracted topic
SELECT
meeting_title,
meeting_date,
topic.value::STRING as topic
FROM meeting_transcripts,
LATERAL FLATTEN(input => ai_extracted_topics) topic
WHERE topic.value::STRING ILIKE '%security%'
ORDER BY meeting_date DESC;
This auto-tagging makes meetings even more discoverable without manual categorization.
Cost Optimization Tips
Running LLMs on every query can get expensive. Here are strategies to keep costs reasonable:
-- Strategy 1: Response caching
CREATE OR REPLACE TABLE answer_cache (
question_hash STRING PRIMARY KEY,
question STRING,
cached_answer VARIANT,
cached_at TIMESTAMP_LTZ,
cache_hits INTEGER DEFAULT 0
);
-- Modified function with caching
CREATE OR REPLACE FUNCTION ask_with_cache(question STRING)
RETURNS VARIANT
LANGUAGE SQL
AS
$$
SELECT
COALESCE(
-- Try cache first
(SELECT cached_answer
FROM answer_cache
WHERE question_hash = SHA2(LOWER(TRIM(question)))
AND cached_at >= DATEADD(hour, -24, CURRENT_TIMESTAMP())
LIMIT 1),
-- Generate new answer if not cached
ask_meeting_assistant(question)
)
$$;
-- Strategy 2: Smaller model for simple queries
CREATE OR REPLACE FUNCTION ask_simple(question STRING)
RETURNS VARIANT
LANGUAGE SQL
AS
$$
-- Use smaller, cheaper model for straightforward questions
-- Use llama3.1-8b instead of llama3.1-70b for basic lookups
WITH relevant_meetings AS (
SELECT
chunk_text,
chunk_metadata:meeting_title::STRING as meeting_title,
chunk_metadata:meeting_date::TIMESTAMP_LTZ as meeting_date
FROM TABLE(
meeting_search_service!SEARCH(
QUERY => question,
LIMIT => 2 -- Fewer chunks = lower cost
)
)
),
context_builder AS (
SELECT
LISTAGG(
'Meeting: ' || meeting_title || '\n' || chunk_text,
'\n\n---\n\n'
) as combined_context
FROM relevant_meetings
)
SELECT OBJECT_CONSTRUCT(
'answer', SNOWFLAKE.CORTEX.COMPLETE(
'llama3.1-8b', -- Cheaper model
'Answer briefly based on these meeting notes: ' || combined_context ||
'\n\nQuestion: ' || question
)
)
FROM context_builder
$$;
-- Strategy 3: Batch processing for reports
-- Instead of asking individual questions, batch them
CREATE OR REPLACE PROCEDURE generate_weekly_summary()
RETURNS VARIANT
LANGUAGE SQL
AS
$$
DECLARE
result VARIANT;
BEGIN
-- Get all meetings from last week
WITH last_week_meetings AS (
SELECT
LISTAGG(
'Meeting: ' || meeting_title ||
'\nDate: ' || meeting_date ||
'\nKey points: ' || transcript_text,
'\n\n---\n\n'
) as all_meetings
FROM meeting_transcripts
WHERE meeting_date >= DATEADD(week, -1, CURRENT_TIMESTAMP())
)
SELECT OBJECT_CONSTRUCT(
'summary', SNOWFLAKE.CORTEX.SUMMARIZE(all_meetings),
'key_decisions', SNOWFLAKE.CORTEX.COMPLETE(
'llama3.1-70b',
'List all key decisions made in these meetings: ' || all_meetings
),
'action_items', SNOWFLAKE.CORTEX.COMPLETE(
'llama3.1-70b',
'List all action items from these meetings: ' || all_meetings
)
) INTO result
FROM last_week_meetings;
RETURN result;
END;
$$;
These optimization strategies can cut costs by 40-60% while maintaining quality for most queries.
Quality Assurance: Building a Test Suite
We should validate that our RAG system returns accurate answers:
-- Create test cases table
CREATE OR REPLACE TABLE rag_test_cases (
test_id INTEGER AUTOINCREMENT,
test_question STRING,
expected_answer_contains STRING,
expected_meeting_reference STRING,
test_category STRING,
created_at TIMESTAMP_LTZ DEFAULT CURRENT_TIMESTAMP()
);
-- Add test cases based on our sample data
INSERT INTO rag_test_cases (test_question, expected_answer_contains, expected_meeting_reference, test_category)
VALUES
('Why did we choose PostgreSQL?', 'JSON support', 'Database Migration Discussion', 'decision_lookup'),
('What are Mike\'s action items?', 'rate limiting', 'API Security Review', 'action_item_lookup'),
('When is the dashboard launch?', 'February 28', 'Q1 Product Planning', 'timeline_lookup'),
('What security issues were found?', 'rate limiting', 'API Security Review', 'problem_identification'),
('Who attended the planning meeting?', 'Sarah Chen', 'Q1 Product Planning', 'attendee_lookup');
-- Run test suite
CREATE OR REPLACE PROCEDURE run_rag_tests()
RETURNS TABLE (
test_id INTEGER,
question STRING,
passed BOOLEAN,
answer STRING,
reason STRING
)
LANGUAGE SQL
AS
$$
DECLARE
result_cursor CURSOR FOR
WITH test_results AS (
SELECT
t.test_id,
t.test_question,
ask_meeting_assistant(t.test_question) as answer_obj,
t.expected_answer_contains,
t.expected_meeting_reference
FROM rag_test_cases t
)
SELECT
test_id,
test_question as question,
(
answer_obj:answer::STRING ILIKE '%' || expected_answer_contains || '%'
AND ARRAY_TO_STRING(answer_obj:sources, ',') ILIKE '%' || expected_meeting_reference || '%'
) as passed,
answer_obj:answer::STRING as answer,
CASE
WHEN answer_obj:answer::STRING ILIKE '%' || expected_answer_contains || '%' THEN 'Answer contains expected content'
ELSE 'Missing expected content: ' || expected_answer_contains
END as reason
FROM test_results;
BEGIN
OPEN result_cursor;
RETURN TABLE(result_cursor);
END;
$$;
-- Run tests
CALL run_rag_tests();
This automated testing ensures our RAG system maintains quality as we add more meetings and refine prompts.
Monitoring and Alerts
Set up monitoring to catch issues early:
-- Create monitoring table
CREATE OR REPLACE TABLE rag_health_metrics (
metric_date DATE,
total_queries INTEGER,
avg_response_time_seconds FLOAT,
successful_queries INTEGER,
failed_queries INTEGER,
avg_satisfaction_score FLOAT,
unique_users INTEGER
);
-- Daily health check task
CREATE OR REPLACE TASK daily_health_check
WAREHOUSE = meeting_rag_wh
SCHEDULE = 'USING CRON 0 8 * * * America/Los_Angeles' -- 8 AM daily
AS
INSERT INTO rag_health_metrics
SELECT
CURRENT_DATE() as metric_date,
COUNT(*) as total_queries,
AVG(DATEDIFF(second, queried_at, CURRENT_TIMESTAMP())) as avg_response_time_seconds,
COUNT(CASE WHEN answer IS NOT NULL THEN 1 END) as successful_queries,
COUNT(CASE WHEN answer IS NULL THEN 1 END) as failed_queries,
AVG(CASE WHEN helpful_vote = 1 THEN 1.0
WHEN helpful_vote = -1 THEN 0.0
ELSE NULL END) as avg_satisfaction_score,
COUNT(DISTINCT user_name) as unique_users
FROM meeting_assistant_logs
WHERE queried_at >= DATEADD(day, -1, CURRENT_DATE());
-- Resume health check task
ALTER TASK daily_health_check RESUME;
-- Alert query (run this manually or set up notifications)
SELECT
metric_date,
total_queries,
avg_satisfaction_score,
CASE
WHEN avg_satisfaction_score < 0.7 THEN '⚠️ LOW SATISFACTION'
WHEN failed_queries > total_queries * 0.1 THEN '⚠️ HIGH FAILURE RATE'
ELSE '✅ HEALTHY'
END as status
FROM rag_health_metrics
WHERE metric_date >= DATEADD(day, -7, CURRENT_DATE())
ORDER BY metric_date DESC;
Advanced: Multi-Turn Conversations
Right now, each question is independent. We can add conversation context:
-- Table to track conversation sessions
CREATE OR REPLACE TABLE conversation_sessions (
session_id STRING PRIMARY KEY,
user_name STRING,
started_at TIMESTAMP_LTZ DEFAULT CURRENT_TIMESTAMP(),
last_interaction TIMESTAMP_LTZ DEFAULT CURRENT_TIMESTAMP(),
conversation_history ARRAY
);
-- Function with conversation memory
CREATE OR REPLACE FUNCTION ask_with_context(
session_id STRING,
user_name STRING,
current_question STRING
)
RETURNS VARIANT
LANGUAGE SQL
AS
$$
WITH session_data AS (
SELECT
COALESCE(conversation_history, ARRAY_CONSTRUCT()) as history
FROM conversation_sessions
WHERE session_id = session_id
LIMIT 1
),
enhanced_question AS (
SELECT
CASE
WHEN ARRAY_SIZE(history) > 0 THEN
current_question || ' (Context from previous questions: ' ||
ARRAY_TO_STRING(history, ', ') || ')'
ELSE current_question
END as full_question
FROM session_data
)
SELECT ask_meeting_assistant(full_question)
FROM enhanced_question
$$;
This allows follow-up questions like:
User: “What did we decide about the database?”
System: “We chose PostgreSQL…”
User: “Why that over MySQL?” ← understands “that” refers to PostgreSQL
Example Use Cases in Action
Let’s see how different teams would use this:
Engineering Team:
-- Find all technical decisions
SELECT
result:answer::STRING as answer
FROM (
SELECT ask_meeting_assistant(
'What technical decisions were made in the last month?'
) as result
);
-- Get status of specific feature
SELECT
result:answer::STRING as answer
FROM (
SELECT ask_meeting_assistant(
'What is the current status of the Redis implementation?'
) as result
);
Product Team:
-- Customer feedback summary
SELECT
result:answer::STRING as answer
FROM (
SELECT ask_meeting_assistant(
'What customer feedback have we received about the dashboard?'
) as result
);
-- Feature prioritization
SELECT
result:answer::STRING as answer
FROM (
SELECT ask_meeting_assistant(
'What features are prioritized for Q2?'
) as result
);
Management:
-- Project blockers
SELECT
result:answer::STRING as answer
FROM (
SELECT ask_meeting_assistant(
'What are the current blockers for the product launch?'
) as result
);
-- Team action items
SELECT * FROM TABLE(get_action_items_for('engineering team'));
Extending to Other Data Sources
The beautiful thing about this architecture is it’s extensible. We can add other knowledge sources:
-- Add Jira tickets
CREATE TABLE jira_issues (
issue_key STRING,
summary STRING,
description STRING,
status STRING,
created_date TIMESTAMP_LTZ
);
-- Add Slack discussions
CREATE TABLE slack_threads (
thread_id STRING,
channel_name STRING,
message_text STRING,
posted_at TIMESTAMP_LTZ
);
-- Add Confluence docs
CREATE TABLE wiki_pages (
page_id STRING,
title STRING,
content STRING,
last_updated TIMESTAMP_LTZ
);
-- Unified search across all sources
CREATE OR REPLACE FUNCTION ask_everything(question STRING)
RETURNS VARIANT
LANGUAGE SQL
AS
$$
-- Implementation would search across all sources
-- and combine results intelligently
$$;
Now your RAG system becomes a true organizational knowledge hub.
What We’ve Built
Let’s recap what this system can do:
✅ Natural language search across all meeting notes ✅ Intelligent answers with source citations ✅ Action item tracking by person and date ✅ Decision history with full context ✅ Topic extraction and categorization ✅ Multi-turn conversations with context memory ✅ Automated ingestion of new meetings ✅ Quality monitoring and testing ✅ Cost optimization through caching ✅ Integration ready for Slack, Teams, etc.
And all of this runs entirely within Snowflake—no external services, no data movement, no infrastructure headaches.
The Real Value Proposition
Here’s what changes when we have a system like this:
Before:
Someone asks “What did we decide about X?”
You spend 20 minutes searching through meeting notes
You find partial information across 3 different meetings
You piece together an answer, but you’re not 100% sure
Total time wasted: 20+ minutes
After:
Someone asks “What did we decide about X?”
You type the question into the assistant
Get a complete answer with sources in 2 seconds
Click through to verify if needed
Total time: 30 seconds
That’s a 40x improvement. Multiply that across your entire team, every day, and the ROI becomes obvious.
Future Enhancements We Can Build
This is just the foundation. Here are ideas for taking it further:
Automatic summaries: Email digest every Monday with key decisions from last week
Proactive alerts: “You have 3 action items due this week”
Meeting preparation: “Here’s what was discussed last time you met with this team”
Trend analysis: “Database migration has been mentioned 15 times this month”
Sentiment tracking: Detect when team morale shifts in meetings
Smart reminders: “You committed to X in the meeting but haven’t updated status”
The possibilities are endless once we have meeting data structured and searchable.
Final Thoughts
The technology for this has existed for years, but what’s changed is how accessible it’s become. Building a RAG system used to require:
Deep ML expertise
Complex infrastructure
Weeks of development time
Ongoing maintenance burden
Now, with Snowflake Cortex, we can build it in a weekend using SQL. That’s the real revolution—not the technology itself, but the democratization of it.
Every organization has the same problem: valuable knowledge trapped in meeting notes that nobody ever looks at again. We’ve just seen how to solve that problem in a practical, maintainable way.
The question isn’t “Can we build this?” anymore. It’s “When do we start?”
-- Complete setup script for Meeting Notes RAG
-- Run this entire script to set up the system
-- 1. Database setup
CREATE DATABASE IF NOT EXISTS meeting_intelligence;
USE DATABASE meeting_intelligence;
CREATE SCHEMA IF NOT EXISTS meetings;
USE SCHEMA meetings;
-- 2. Compute
CREATE WAREHOUSE IF NOT EXISTS meeting_rag_wh
WITH WAREHOUSE_SIZE = 'SMALL'
AUTO_SUSPEND = 60
AUTO_RESUME = TRUE;
USE WAREHOUSE meeting_rag_wh;
-- 3. Main tables
CREATE OR REPLACE TABLE meeting_transcripts (
meeting_id STRING PRIMARY KEY,
meeting_title STRING NOT NULL,
meeting_date TIMESTAMP_LTZ NOT NULL,
meeting_type STRING,
attendees ARRAY,
transcript_text STRING NOT NULL,
action_items ARRAY,
decisions_made ARRAY,
topics_discussed ARRAY
);
CREATE OR REPLACE TABLE meeting_chunks (
chunk_id STRING PRIMARY KEY,
meeting_id STRING,
chunk_text STRING,
chunk_metadata VARIANT,
chunk_embedding VECTOR(FLOAT, 1024)
);
-- 4. Load sample data (use the INSERT statements from earlier)
-- 5. Create embeddings and search service
UPDATE meeting_chunks
SET chunk_embedding = SNOWFLAKE.CORTEX.EMBED_TEXT_1024(
'snowflake-arctic-embed-l',
chunk_text
);
CREATE OR REPLACE CORTEX SEARCH SERVICE meeting_search_service
ON chunk_text
WAREHOUSE = meeting_rag_wh
TARGET_LAG = '1 minute'
AS (
SELECT chunk_id, chunk_text, chunk_metadata, chunk_embedding
FROM meeting_chunks
);
-- 6. Create query function (use function from earlier)
-- 7. Test it!
SELECT ask_meeting_assistant('What are the current project blockers?');
When I first heard about building Retrieval-Augmented Generation (RAG) systems directly in Snowflake, I was skeptical that a data warehouse could handle AI workloads this cleanly. After many hours experimenting with Snowflake Cortex Search, I changed my mind.
This guide is for data engineers who already work in Snowflake and want a working RAG application without running a separate vector database. You will build a document table, a Cortex Search service, a SQL function that retrieves context and calls an LLM, and then the production pieces around it: filtering, caching, logging, security, testing and cost monitoring.
Why Build RAG in Snowflake
What RAG is
Retrieval-Augmented Generation combines a large language model with your own data. Instead of relying only on what the model learned during training, a RAG system retrieves relevant passages from your documents and passes them to the model as context, so the answer is grounded in your content and stays current.
Think of it as giving an assistant access to your company’s knowledge base before it answers. The answers are more accurate and more relevant because they come from your actual data.
Why I chose Snowflake
These were my reasons for building RAG in Snowflake rather than on a separate stack:
Your data is already there. No need to move it between systems.
Built-in security. The documents stay under Snowflake’s existing security controls.
Simpler architecture. There is no separate vector database to manage.
Cost-effective. You pay only for what you use.
Scale. It handles millions of documents.
I once spent weeks setting up a separate vector database, managing embeddings and dealing with synchronization issues between it and the source data. With Cortex Search, that layer goes away.
Build the RAG Pipeline Step by Step
Prerequisites
A Snowflake account (a trial account works)
ACCOUNTADMIN or a role with the privileges to create databases, warehouses and Cortex Search services
Basic SQL
Some sample documents (PDFs, text files or structured data)
Step 1: Set up the environment
I always keep RAG projects in a dedicated database for better organization.
-- Create a database for our RAG project
CREATE DATABASE IF NOT EXISTS RAG_PROJECT;
-- Create a schema for our documents
CREATE SCHEMA IF NOT EXISTS RAG_PROJECT.DOCUMENT_STORE;
-- Set the context
USE DATABASE RAG_PROJECT;
USE SCHEMA DOCUMENT_STORE;
-- Create a warehouse for our workload
CREATE WAREHOUSE IF NOT EXISTS RAG_WAREHOUSE
WITH WAREHOUSE_SIZE = 'MEDIUM'
AUTO_SUSPEND = 60
AUTO_RESUME = TRUE;
USE WAREHOUSE RAG_WAREHOUSE;
Start with a MEDIUM warehouse. You can scale up later, but for most RAG workloads this size is the right starting point.
Step 2: Prepare the document data
For this walkthrough I use a product documentation knowledge base, a scenario I have built for a client.
-- Create a table to store our documents
CREATE OR REPLACE TABLE PRODUCT_DOCUMENTATION (
DOC_ID VARCHAR(100),
TITLE VARCHAR(500),
CONTENT TEXT,
CATEGORY VARCHAR(100),
LAST_UPDATED TIMESTAMP_NTZ DEFAULT CURRENT_TIMESTAMP(),
METADATA VARIANT
);
-- Insert sample product documentation
INSERT INTO PRODUCT_DOCUMENTATION (DOC_ID, TITLE, CONTENT, CATEGORY, METADATA)
VALUES
(
'DOC001',
'Getting Started with CloudSync Pro',
'CloudSync Pro is an enterprise file synchronization solution that enables seamless collaboration across teams.
To get started, first download the desktop client from our portal. Install the application and sign in using your
corporate credentials. The initial sync may take several hours depending on your data volume. We recommend starting
with smaller folders and gradually adding more. CloudSync Pro supports real-time synchronization, version control,
and automatic conflict resolution. For optimal performance, ensure your network connection is stable and your
firewall allows traffic on ports 443 and 8080.',
'Getting Started',
PARSE_JSON('{"version": "3.2", "author": "Technical Writing Team", "views": 15420}')
),
(
'DOC002',
'Troubleshooting Connection Issues',
'If you are experiencing connection issues with CloudSync Pro, follow these steps: First, verify your internet
connectivity by accessing other websites. Check if your firewall or antivirus is blocking the application.
CloudSync Pro requires outbound HTTPS connections on port 443. Navigate to Settings > Network and click Test
Connection. If the test fails, review your proxy settings. For corporate networks, you may need to configure
proxy authentication. Common error codes: ERR_001 indicates firewall blocking, ERR_002 means invalid credentials,
ERR_003 suggests server maintenance. If issues persist, collect logs from Help > Generate Support Bundle and
contact our support team.',
'Troubleshooting',
PARSE_JSON('{"version": "3.2", "author": "Support Team", "views": 8932}')
),
(
'DOC003',
'Advanced Security Features',
'CloudSync Pro offers enterprise-grade security features including end-to-end encryption, zero-knowledge architecture,
and compliance with SOC 2 Type II, GDPR, and HIPAA requirements. All data is encrypted using AES-256 encryption both
in transit and at rest. Administrators can enforce two-factor authentication, set password complexity requirements,
and configure session timeouts. The Data Loss Prevention (DLP) module scans files for sensitive information like
credit card numbers and social security numbers. Audit logs track all user activities including file access, sharing,
and deletions. For enhanced security, enable the Remote Wipe feature which allows administrators to delete company
data from lost or stolen devices.',
'Security',
PARSE_JSON('{"version": "3.2", "author": "Security Team", "views": 5643}')
),
(
'DOC004',
'Pricing and License Management',
'CloudSync Pro offers flexible pricing plans: Starter plan at $10/user/month includes 100GB storage, Standard plan
at $25/user/month includes 1TB storage and priority support, Enterprise plan at $50/user/month includes unlimited
storage and dedicated account manager. Annual subscriptions receive 20% discount. License management is handled
through the Admin Portal. To add users, navigate to Users > Add User and enter their email address. Licenses are
automatically assigned upon invitation acceptance. You can upgrade or downgrade plans at any time with prorated
billing. Volume discounts available for organizations with 100+ users. Educational institutions receive 50% discount
with valid credentials.',
'Pricing',
PARSE_JSON('{"version": "3.2", "author": "Sales Team", "views": 12876}')
),
(
'DOC005',
'API Integration Guide',
'CloudSync Pro provides a comprehensive REST API for custom integrations. Authentication uses OAuth 2.0 with API
keys available in the Developer section of your dashboard. Base URL: https://api.cloudsyncpro.com/v1. Key endpoints
include: /files for file operations, /users for user management, /shares for collaboration features. Rate limits
apply: 1000 requests per hour for Standard plans, 5000 for Enterprise. All requests must include the Authorization
header with your API key. Responses are in JSON format. Sample request to upload a file: POST /files with
multipart/form-data containing the file and metadata. Webhooks are available for real-time notifications of file
changes, sharing events, and user activities. SDK libraries available for Python, JavaScript, Java, and .NET.',
'API Documentation',
PARSE_JSON('{"version": "3.2", "author": "Engineering Team", "views": 4521}')
);
-- Verify our data
SELECT DOC_ID, TITLE, CATEGORY FROM PRODUCT_DOCUMENTATION;
The table holds one row per document with a free-text CONTENT column (the part that gets searched), a CATEGORY you can filter on later, and a VARIANT METADATA column for version, author and view counts. Replace the five INSERT rows with your own documents; the final SELECT just confirms they loaded.
Step 3: Create a Cortex Search service
Cortex Search handles the embeddings, the vector index and the semantic search for you.
-- Create a Cortex Search Service
CREATE OR REPLACE CORTEX SEARCH SERVICE PRODUCT_DOCS_SEARCH
ON CONTENT
WAREHOUSE = RAG_WAREHOUSE
TARGET_LAG = '1 hour'
AS (
SELECT
DOC_ID,
CONTENT,
TITLE,
CATEGORY,
LAST_UPDATED
FROM PRODUCT_DOCUMENTATION
);
When this runs, Snowflake:
generates embeddings for the CONTENT column,
builds a search index,
sets up incremental refresh according to TARGET_LAG, and
makes the service queryable from SQL.
The first time I ran this, the setup that used to take me hours of embedding generation and vector database configuration finished in seconds.
Step 4: Testing Your Search Service
Let’s make sure everything is working correctly:
-- Check search service status
SHOW CORTEX SEARCH SERVICES;
-- Test a basic search query
SELECT
PARSE_JSON(results) as search_results
FROM TABLE(
RAG_PROJECT.DOCUMENT_STORE.PRODUCT_DOCS_SEARCH!SEARCH(
'How do I fix connection problems?',
1
)
);
This checks that the service exists and returns the single most relevant document for a question about connection problems.
Step 5: Building the RAG Query Function
The RAG function does three things: search for relevant documents, combine their content into a context string, and pass that context to an LLM to generate the answer.
-- Create a function that performs RAG
CREATE OR REPLACE FUNCTION ASK_PRODUCT_DOCS(question VARCHAR)
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
WITH search_results AS (
SELECT
value:doc_id::VARCHAR as doc_id,
value:content::VARCHAR as content,
value:title::VARCHAR as title
FROM TABLE(
RAG_PROJECT.DOCUMENT_STORE.PRODUCT_DOCS_SEARCH!SEARCH(
question,
3 -- Get top 3 most relevant documents
)
),
LATERAL FLATTEN(input => PARSE_JSON(results))
),
context AS (
SELECT
LISTAGG(
'Document: ' || title || '\n' ||
'Content: ' || content,
'\n\n---\n\n'
) as combined_context
FROM search_results
)
SELECT
SNOWFLAKE.CORTEX.COMPLETE(
'mistral-large2',
CONCAT(
'You are a helpful product documentation assistant. ',
'Use the following documentation to answer the user question. ',
'If the answer is not in the documentation, say you don\'t know. ',
'Be concise and accurate.\n\n',
'Documentation:\n',
combined_context,
'\n\nUser Question: ',
question,
'\n\nAnswer:'
)
) as answer
FROM context
$$;
This function is the core of the system:
search_results CTE: asks Cortex Search for the 3 most relevant documents.
context CTE: joins the retrieved documents into one context string with LISTAGG, separated by ---.
COMPLETE: sends that context plus the question to the language model, with an instruction to say “I don’t know” when the answer is not in the documentation.
I usually use mistral-large2 for RAG because it is fast and cost-effective. For more complex reasoning you can switch to llama3.1-405b by changing the first argument to COMPLETE.
Step 6: Querying Your RAG System
Now for the exciting part – let’s ask some questions!
-- Example 1: Technical support question
SELECT ASK_PRODUCT_DOCS('How do I troubleshoot connection issues?') as answer;
-- Example 2: Pricing inquiry
SELECT ASK_PRODUCT_DOCS('What are the different pricing plans available?') as answer;
-- Example 3: Security question
SELECT ASK_PRODUCT_DOCS('What security certifications does CloudSync Pro have?') as answer;
-- Example 4: Integration question
SELECT ASK_PRODUCT_DOCS('How can I integrate CloudSync Pro with my application?') as answer;
Each answer is drawn from the documents loaded in Step 2 and formatted as a direct reply to the question.
Step 7: Filter by metadata and add conversation history
Filtering by Metadata
Being able to filter search results is one of the features I like most in Cortex Search. This version only searches security documents:
-- Search only security-related documents
CREATE OR REPLACE FUNCTION ASK_SECURITY_DOCS(question VARCHAR)
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
WITH search_results AS (
SELECT
value:content::VARCHAR as content,
value:title::VARCHAR as title
FROM TABLE(
RAG_PROJECT.DOCUMENT_STORE.PRODUCT_DOCS_SEARCH!SEARCH(
question,
3,
{'filter': {'@eq': {'category': 'Security'}}}
)
),
LATERAL FLATTEN(input => PARSE_JSON(results))
),
context AS (
SELECT
LISTAGG(
'Document: ' || title || '\n' ||
'Content: ' || content,
'\n\n---\n\n'
) as combined_context
FROM search_results
)
SELECT
SNOWFLAKE.CORTEX.COMPLETE(
'mistral-large2',
CONCAT(
'You are a security documentation expert. ',
'Use only the security documentation provided to answer questions. ',
'Be precise about security features and compliance.\n\n',
'Documentation:\n',
combined_context,
'\n\nQuestion: ',
question,
'\n\nAnswer:'
)
) as answer
FROM context
$$;
-- Test security-specific query
SELECT ASK_SECURITY_DOCS('What encryption does the product use?') as answer;
The only differences from ASK_PRODUCT_DOCS are the third argument to SEARCH, which restricts results to category = 'Security', and a prompt written for a security audience.
Conversation history
To build a chatbot, pass the previous turns in as a second argument:
CREATE OR REPLACE FUNCTION ASK_WITH_HISTORY(
question VARCHAR,
conversation_history VARCHAR
)
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
WITH search_results AS (
SELECT
value:content::VARCHAR as content,
value:title::VARCHAR as title
FROM TABLE(
RAG_PROJECT.DOCUMENT_STORE.PRODUCT_DOCS_SEARCH!SEARCH(
question,
3
)
),
LATERAL FLATTEN(input => PARSE_JSON(results))
),
context AS (
SELECT
LISTAGG(
'Document: ' || title || '\n' ||
'Content: ' || content,
'\n\n---\n\n'
) as combined_context
FROM search_results
)
SELECT
SNOWFLAKE.CORTEX.COMPLETE(
'mistral-large2',
CONCAT(
'You are a helpful product assistant. Use the documentation and conversation history to answer. ',
'Be conversational and reference previous context when relevant.\n\n',
'Previous Conversation:\n',
conversation_history,
'\n\nDocumentation:\n',
combined_context,
'\n\nCurrent Question: ',
question,
'\n\nAnswer:'
)
) as answer
FROM context
$$;
The retrieval step is the same. The prompt now includes a “Previous Conversation” block before the documentation, so the model can refer back to earlier questions. Your application is responsible for building and passing the conversation_history string.
Step 8: Wrap it for applications
For applications I add a simpler entry point:
-- Create a view for easy querying
CREATE OR REPLACE VIEW PRODUCT_DOCS_QA AS
SELECT
'Use: SELECT * FROM PRODUCT_DOCS_QA WHERE question = ''your question here''' as usage_instructions
UNION ALL
SELECT
'Available categories: Getting Started, Troubleshooting, Security, Pricing, API Documentation'
;
-- Create a procedure for interactive queries
CREATE OR REPLACE PROCEDURE ASK_DOCS(QUESTION VARCHAR)
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
BEGIN
LET answer VARCHAR;
answer := (SELECT ASK_PRODUCT_DOCS(:QUESTION));
RETURN answer;
END;
$$;
-- Test the procedure
CALL ASK_DOCS('What is the rate limit for API calls?');
The view only returns usage instructions as text. The useful part is the ASK_DOCS procedure, which wraps ASK_PRODUCT_DOCS so callers can use CALL ASK_DOCS('...').
Step 9: Monitor and maintain
I learned the hard way that you need to monitor a RAG system from the start.
-- Check search service performance
SELECT
SERVICE_NAME,
DATABASE_NAME,
SCHEMA_NAME,
SEARCH_COLUMN,
CREATED_ON,
REFRESHED_ON
FROM TABLE(
INFORMATION_SCHEMA.CORTEX_SEARCH_SERVICES(
DATABASE_NAME => 'RAG_PROJECT',
SCHEMA_NAME => 'DOCUMENT_STORE'
)
);
-- Create a logging table for queries
CREATE OR REPLACE TABLE QUERY_LOG (
QUERY_ID VARCHAR(100) DEFAULT UUID_STRING(),
QUESTION TEXT,
ANSWER TEXT,
EXECUTION_TIME NUMBER(10,2),
TIMESTAMP TIMESTAMP_NTZ DEFAULT CURRENT_TIMESTAMP()
);
-- Enhanced function with logging
CREATE OR REPLACE FUNCTION ASK_PRODUCT_DOCS_WITH_LOG(question VARCHAR)
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
WITH search_results AS (
SELECT
value:content::VARCHAR as content,
value:title::VARCHAR as title
FROM TABLE(
RAG_PROJECT.DOCUMENT_STORE.PRODUCT_DOCS_SEARCH!SEARCH(
question,
3
)
),
LATERAL FLATTEN(input => PARSE_JSON(results))
),
context AS (
SELECT
LISTAGG(
'Document: ' || title || '\n' ||
'Content: ' || content,
'\n\n---\n\n'
) as combined_context
FROM search_results
),
answer_result AS (
SELECT
SNOWFLAKE.CORTEX.COMPLETE(
'mistral-large2',
CONCAT(
'You are a helpful product documentation assistant. ',
'Use the following documentation to answer the user question. ',
'If the answer is not in the documentation, say you don\'t know.\n\n',
'Documentation:\n',
combined_context,
'\n\nQuestion: ',
question,
'\n\nAnswer:'
)
) as answer
FROM context
)
SELECT answer FROM answer_result
$$;
The first query lists the search services in the schema with their creation and last refresh times. The QUERY_LOG table gives you somewhere to record questions, answers and execution time. Note that ASK_PRODUCT_DOCS_WITH_LOG, despite its name, does not write to QUERY_LOG: it returns the answer the same way as ASK_PRODUCT_DOCS, so you need to add the insert in your application or a procedure.
Step 10: Update the knowledge base
New documents are picked up automatically. Insert them into the source table:
-- Add new documentation
INSERT INTO PRODUCT_DOCUMENTATION (DOC_ID, TITLE, CONTENT, CATEGORY, METADATA)
VALUES
(
'DOC006',
'Mobile App Configuration',
'The CloudSync Pro mobile app is available for iOS and Android devices. Download from the App Store or Google Play.
After installation, tap Sign In and enter your credentials. Enable biometric authentication for quick access.
Configure sync settings under Settings > Sync Options. You can choose to sync over Wi-Fi only to save mobile data.
Enable camera upload to automatically backup photos and videos. The app supports offline access - files are cached
locally and sync when connection is restored. Battery optimization: disable background refresh if battery life is
a concern. Push notifications can be customized for file sharing, comments, and mentions.',
'Mobile',
PARSE_JSON('{"version": "3.2", "author": "Mobile Team", "views": 7234}')
);
-- The Cortex Search Service automatically updates based on TARGET_LAG
-- Wait for the target lag period (1 hour in our case), then test:
SELECT ASK_PRODUCT_DOCS('How do I configure the mobile app?') as answer;
The service refreshes according to TARGET_LAG, so with the 1 hour setting from Step 3 the new document becomes searchable within about an hour.
Two Real-World Use Cases
Let me share some scenarios where this RAG setup has been incredibly valuable:
Customer support portal
I built a customer-facing chatbot on this pattern that reduced support tickets by 40%. The key was making the assistant aware of the customer’s plan so it gave relevant answers:
-- Category-aware support function
CREATE OR REPLACE FUNCTION SUPPORT_ASSISTANT(
question VARCHAR,
user_plan VARCHAR -- 'Starter', 'Standard', 'Enterprise'
)
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
WITH search_results AS (
SELECT
value:content::VARCHAR as content,
value:title::VARCHAR as title,
value:category::VARCHAR as category
FROM TABLE(
RAG_PROJECT.DOCUMENT_STORE.PRODUCT_DOCS_SEARCH!SEARCH(
question,
5
)
),
LATERAL FLATTEN(input => PARSE_JSON(results))
),
context AS (
SELECT
LISTAGG(
'Document: ' || title || ' (Category: ' || category || ')\n' ||
'Content: ' || content,
'\n\n---\n\n'
) as combined_context
FROM search_results
)
SELECT
SNOWFLAKE.CORTEX.COMPLETE(
'mistral-large2',
CONCAT(
'You are a customer support assistant. The user has a ',
user_plan,
' plan. Use the documentation to help them. ',
'If a feature is not available in their plan, mention upgrade options.\n\n',
'Documentation:\n',
combined_context,
'\n\nCustomer Question: ',
question,
'\n\nResponse:'
)
) as answer
FROM context
$$;
-- Test with different user plans
SELECT SUPPORT_ASSISTANT('Can I use the API?', 'Starter') as starter_response;
SELECT SUPPORT_ASSISTANT('Can I use the API?', 'Enterprise') as enterprise_response;
This version retrieves 5 documents instead of 3, includes each document’s category in the context, and passes the customer’s plan into the prompt so the model can mention upgrade options when a feature is not included. The two test calls show the same question answered for a Starter and an Enterprise customer.
Internal knowledge management
For a Fortune 500 client, I built an internal wiki search that their executives liked. The function returns a short structured summary rather than a direct answer:
-- Executive summary function
CREATE OR REPLACE FUNCTION EXECUTIVE_SUMMARY(topic VARCHAR)
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
WITH search_results AS (
SELECT
value:content::VARCHAR as content,
value:title::VARCHAR as title
FROM TABLE(
RAG_PROJECT.DOCUMENT_STORE.PRODUCT_DOCS_SEARCH!SEARCH(
topic,
5
)
),
LATERAL FLATTEN(input => PARSE_JSON(results))
),
context AS (
SELECT
LISTAGG(
'Document: ' || title || '\n' ||
'Content: ' || content,
'\n\n---\n\n'
) as combined_context
FROM search_results
)
SELECT
SNOWFLAKE.CORTEX.COMPLETE(
'mistral-large2',
CONCAT(
'Create a concise executive summary about: ',
topic,
'\n\nUse these documents as sources:\n',
combined_context,
'\n\nProvide:\n',
'1. Key Points (3-5 bullets)\n',
'2. Business Impact\n',
'3. Recommended Actions\n\n',
'Keep it under 200 words. Be strategic and actionable.'
)
) as summary
FROM context
$$;
SELECT EXECUTIVE_SUMMARY('product security and compliance') as exec_summary;
The retrieval is unchanged. The prompt asks for key points, business impact and recommended actions in under 200 words, which suits a topic-level question better than a single fact lookup.
Performance and Cost
These are the lessons I took from building several RAG systems.
Chunk large documents
If your documents are long, split them into smaller chunks before indexing:
-- Create a chunked version of documents
CREATE OR REPLACE TABLE PRODUCT_DOCUMENTATION_CHUNKED AS
WITH RECURSIVE chunks AS (
SELECT
DOC_ID,
TITLE,
CATEGORY,
CONTENT,
1 as chunk_num,
SUBSTR(CONTENT, 1, 1000) as chunk_content,
LENGTH(CONTENT) as total_length
FROM PRODUCT_DOCUMENTATION
UNION ALL
SELECT
DOC_ID,
TITLE,
CATEGORY,
CONTENT,
chunk_num + 1,
SUBSTR(CONTENT, chunk_num * 1000 + 1, 1000),
total_length
FROM chunks
WHERE chunk_num * 1000 < total_length
)
SELECT
DOC_ID || '_CHUNK_' || chunk_num as CHUNK_ID,
DOC_ID,
TITLE,
CATEGORY,
chunk_content as CONTENT,
chunk_num
FROM chunks
WHERE LENGTH(chunk_content) > 0;
-- Create search service on chunked data
CREATE OR REPLACE CORTEX SEARCH SERVICE PRODUCT_DOCS_SEARCH_CHUNKED
ON CONTENT
WAREHOUSE = RAG_WAREHOUSE
TARGET_LAG = '1 hour'
AS (
SELECT
CHUNK_ID,
CONTENT,
TITLE,
CATEGORY,
DOC_ID
FROM PRODUCT_DOCUMENTATION_CHUNKED
);
The recursive CTE cuts each document into 1,000-character pieces and gives each one a CHUNK_ID like DOC001_CHUNK_1. The second statement builds a separate search service on the chunked table. Change the 1000 values to adjust chunk size. This splits on character count, not on sentences or headings, so a chunk can start mid-sentence.
Choose the right model
mistral-7b: fast and cheap, good for simple Q&A
mistral-large2: balanced, and my default
llama3.1-70b: better reasoning for complex questions
llama3.1-405b: best quality, highest cost
Cache frequent answers
-- Create a cache table
CREATE OR REPLACE TABLE ANSWER_CACHE (
QUESTION_HASH VARCHAR(64),
QUESTION TEXT,
ANSWER TEXT,
CACHE_DATE TIMESTAMP_NTZ DEFAULT CURRENT_TIMESTAMP(),
HIT_COUNT NUMBER DEFAULT 1
);
-- Function with caching
CREATE OR REPLACE FUNCTION ASK_WITH_CACHE(question VARCHAR)
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
WITH cache_check AS (
SELECT ANSWER
FROM ANSWER_CACHE
WHERE QUESTION_HASH = SHA2(LOWER(TRIM(question)))
AND CACHE_DATE > DATEADD(hour, -24, CURRENT_TIMESTAMP())
LIMIT 1
)
SELECT
COALESCE(
(SELECT ANSWER FROM cache_check),
ASK_PRODUCT_DOCS(question)
) as final_answer
$$;
ASK_WITH_CACHE looks up a hash of the normalized question and returns a cached answer if one is less than 24 hours old; otherwise it calls ASK_PRODUCT_DOCS. As written, nothing writes new answers into ANSWER_CACHE, so you need a separate step (for example a procedure or your application) that inserts the question hash and answer after each miss.
Keep costs reasonable
Right-size the warehouse. Start small and scale when you need to.
Use AUTO_SUSPEND. Do not pay for idle compute.
Cache frequent questions. Avoid repeat LLM calls.
Match the model to the task. Do not use an expensive model for simple questions.
Set TARGET_LAG sensibly. Hourly refresh is usually enough.
-- Monitor your costs
SELECT
WAREHOUSE_NAME,
SUM(CREDITS_USED) as total_credits,
SUM(CREDITS_USED) * 3 as estimated_cost_usd -- Approximate cost
FROM SNOWFLAKE.ACCOUNT_USAGE.WAREHOUSE_METERING_HISTORY
WHERE START_TIME >= DATEADD(day, -30, CURRENT_TIMESTAMP())
GROUP BY WAREHOUSE_NAME
ORDER BY total_credits DESC;
This totals warehouse credits per warehouse for the last 30 days. The * 3 is a rough dollars-per-credit figure; replace it with your contract rate.
Common Pitfalls and Troubleshooting
Pitfalls to avoid
Poor document structure. Loading entire manuals as single documents. Break them into logical sections with clear titles.
Generic prompts. Not telling the model what role it plays. Always include system instructions and domain context.
Ignoring metadata. Treating every document as equal. Use version numbers, dates and categories to prefer recent, relevant content.
No error handling. Wrap the RAG call so users get a readable message instead of an error:
-- Add error handling
CREATE OR REPLACE FUNCTION ASK_SAFE(question VARCHAR)
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
BEGIN
RETURN ASK_PRODUCT_DOCS(question);
EXCEPTION
WHEN OTHER THEN
RETURN 'I apologize, but I encountered an error processing your question. Please try rephrasing it or contact support.';
END;
$$;
Handling questions with no matching documents
Real users will ask questions your documentation cannot answer. This version checks for that before calling the LLM:
-- Function that handles empty results
CREATE OR REPLACE FUNCTION ASK_ROBUST(question VARCHAR)
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
WITH search_results AS (
SELECT
value:content::VARCHAR as content,
value:title::VARCHAR as title
FROM TABLE(
RAG_PROJECT.DOCUMENT_STORE.PRODUCT_DOCS_SEARCH!SEARCH(
question,
3
)
),
LATERAL FLATTEN(input => PARSE_JSON(results))
),
context AS (
SELECT
LISTAGG(
'Document: ' || title || '\n' ||
'Content: ' || content,
'\n\n---\n\n'
) as combined_context,
COUNT(*) as doc_count
FROM search_results
)
SELECT
CASE
WHEN doc_count = 0 THEN
'I apologize, but I could not find any relevant documentation for your question. ' ||
'Please try rephrasing your question or contact our support team at [email protected].'
ELSE
SNOWFLAKE.CORTEX.COMPLETE(
'mistral-large2',
CONCAT(
'You are a helpful product documentation assistant. ',
'Use the following documentation to answer the user question. ',
'If you are not confident in your answer, say so clearly. ',
'Never make up information.\n\n',
'Documentation:\n',
combined_context,
'\n\nUser Question: ',
question,
'\n\nAnswer:'
)
)
END as answer
FROM context
$$;
-- Test with question that has no answer
SELECT ASK_ROBUST('What is the recipe for chocolate cake?') as answer;
The context CTE also counts the retrieved documents. If the count is zero, the function returns a fixed message instead of calling COMPLETE, and the prompt tells the model never to make up information. The chocolate cake question at the end is a quick way to test the fallback.
Search returns irrelevant results
Improve the metadata and filter on it:
-- Add better metadata
ALTER TABLE PRODUCT_DOCUMENTATION ADD COLUMN TAGS ARRAY;
UPDATE PRODUCT_DOCUMENTATION
SET TAGS = ARRAY_CONSTRUCT('installation', 'setup', 'beginner', 'windows', 'mac')
WHERE DOC_ID = 'DOC001';
-- Use tags in search
CREATE OR REPLACE FUNCTION ASK_WITH_TAGS(question VARCHAR, required_tags ARRAY)
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
-- Implementation with tag filtering
SELECT 'Enhanced search with tag filtering' as result
$$;
The first two statements add a TAGS array and populate it for one document. The ASK_WITH_TAGS function is only a placeholder that returns a fixed string; you need to add your own filtering logic.
Slow response times
Use a bigger warehouse at peak times and cache popular content:
-- Create materialized view for frequently accessed docs
CREATE OR REPLACE MATERIALIZED VIEW POPULAR_DOCS AS
SELECT
d.*,
COUNT(q.QUERY_ID) as access_count
FROM PRODUCT_DOCUMENTATION d
LEFT JOIN QUERY_LOG q ON q.ANSWER LIKE '%' || d.TITLE || '%'
WHERE q.TIMESTAMP > DATEADD(day, -7, CURRENT_TIMESTAMP())
GROUP BY d.DOC_ID, d.TITLE, d.CONTENT, d.CATEGORY, d.LAST_UPDATED, d.METADATA
HAVING access_count > 10;
-- Use larger warehouse for peak times
ALTER WAREHOUSE RAG_WAREHOUSE SET WAREHOUSE_SIZE = 'LARGE';
The view counts how often each document title appeared in answers over the last 7 days and keeps documents seen more than 10 times. The last statement resizes the warehouse to LARGE for peak periods.
Context window exceeded
Truncate long documents before they reach the prompt:
-- Function with context management
CREATE OR REPLACE FUNCTION ASK_WITH_CONTEXT_LIMIT(question VARCHAR)
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
WITH search_results AS (
SELECT
value:content::VARCHAR as content,
value:title::VARCHAR as title,
LENGTH(value:content::VARCHAR) as content_length
FROM TABLE(
RAG_PROJECT.DOCUMENT_STORE.PRODUCT_DOCS_SEARCH!SEARCH(
question,
5
)
),
LATERAL FLATTEN(input => PARSE_JSON(results))
),
truncated_context AS (
SELECT
title,
CASE
WHEN content_length > 1500 THEN
SUBSTR(content, 1, 1500) || '... [truncated]'
ELSE content
END as content
FROM search_results
ORDER BY content_length DESC
LIMIT 3 -- Only top 3 most relevant docs
),
context AS (
SELECT
LISTAGG(
'Document: ' || title || '\n' ||
'Content: ' || content,
'\n\n---\n\n'
) as combined_context
FROM truncated_context
)
SELECT
SNOWFLAKE.CORTEX.COMPLETE(
'mistral-large2',
CONCAT(
'You are a helpful assistant. Answer concisely based on these excerpts:\n\n',
combined_context,
'\n\nQuestion: ',
question,
'\n\nAnswer:'
)
) as answer
FROM context
$$;
This retrieves 5 documents, cuts any document longer than 1,500 characters, and keeps 3 of them. Note that it orders by content length, not by search relevance, so check that this matches what you want.
Deploying to Production
This is my checklist before a RAG system goes live.
Roles and access
-- Create a service role
CREATE ROLE IF NOT EXISTS RAG_SERVICE_ROLE;
-- Grant necessary permissions
GRANT USAGE ON DATABASE RAG_PROJECT TO ROLE RAG_SERVICE_ROLE;
GRANT USAGE ON SCHEMA RAG_PROJECT.DOCUMENT_STORE TO ROLE RAG_SERVICE_ROLE;
GRANT SELECT ON ALL TABLES IN SCHEMA RAG_PROJECT.DOCUMENT_STORE TO ROLE RAG_SERVICE_ROLE;
GRANT USAGE ON WAREHOUSE RAG_WAREHOUSE TO ROLE RAG_SERVICE_ROLE;
-- Grant access to Cortex Search
GRANT USAGE ON CORTEX SEARCH SERVICE PRODUCT_DOCS_SEARCH TO ROLE RAG_SERVICE_ROLE;
API access
-- Create a view for REST API access
CREATE OR REPLACE SECURE VIEW RAG_API AS
SELECT
CURRENT_TIMESTAMP() as query_time,
'POST /api/ask' as endpoint,
'Send JSON: {"question": "your question"}' as usage;
This view only documents the intended endpoint and payload. The actual HTTP calls are in the integration examples below.
Monitoring dashboard
-- Create monitoring view
CREATE OR REPLACE VIEW RAG_MONITORING AS
SELECT
DATE_TRUNC('hour', TIMESTAMP) as hour,
COUNT(*) as query_count,
AVG(EXECUTION_TIME) as avg_response_time
FROM QUERY_LOG
GROUP BY 1
ORDER BY 1 DESC;
This summarises QUERY_LOG by hour: query count and average response time.
Security
Security matters most once a RAG system is exposed to users. This is what I always put in place:
-- Create row-level security policy
CREATE OR REPLACE ROW ACCESS POLICY DOCUMENT_ACCESS_POLICY
AS (user_department VARCHAR)
RETURNS BOOLEAN ->
CASE
WHEN CURRENT_ROLE() IN ('ACCOUNTADMIN', 'SYSADMIN') THEN TRUE
WHEN user_department = CURRENT_USER() THEN TRUE
ELSE FALSE
END;
-- Apply policy to sensitive documents
ALTER TABLE PRODUCT_DOCUMENTATION
ADD ROW ACCESS POLICY DOCUMENT_ACCESS_POLICY ON (CATEGORY);
-- Create audit logging
CREATE OR REPLACE TABLE RAG_AUDIT_LOG (
AUDIT_ID VARCHAR(100) DEFAULT UUID_STRING(),
USER_NAME VARCHAR(100),
USER_ROLE VARCHAR(100),
QUERY_TEXT TEXT,
DOCUMENTS_ACCESSED ARRAY,
ACCESS_GRANTED BOOLEAN,
IP_ADDRESS VARCHAR(50),
TIMESTAMP TIMESTAMP_NTZ DEFAULT CURRENT_TIMESTAMP()
);
-- Function with audit logging
CREATE OR REPLACE FUNCTION ASK_SECURE(question VARCHAR)
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
BEGIN
-- Log access attempt
INSERT INTO RAG_AUDIT_LOG (
USER_NAME,
USER_ROLE,
QUERY_TEXT,
ACCESS_GRANTED
)
VALUES (
CURRENT_USER(),
CURRENT_ROLE(),
question,
TRUE
);
-- Return answer
RETURN ASK_PRODUCT_DOCS(question);
END;
$$;
-- Monitor for suspicious activity
SELECT
USER_NAME,
COUNT(*) as query_count,
COUNT(DISTINCT DATE_TRUNC('hour', TIMESTAMP)) as active_hours
FROM RAG_AUDIT_LOG
WHERE TIMESTAMP > DATEADD(day, -1, CURRENT_TIMESTAMP())
GROUP BY USER_NAME
HAVING query_count > 100 -- Flag high-volume users
ORDER BY query_count DESC;
The block does four things: creates a row access policy and attaches it to the documentation table, creates an audit log table, wraps the RAG call in ASK_SECURE so every question is logged with the user and role, and finally flags any user who asked more than 100 questions in the last day. Adjust the policy logic and the 100-query threshold for your own access model.
Testing
I always build a test suite before release:
-- Create test cases table
CREATE OR REPLACE TABLE RAG_TEST_CASES (
TEST_ID VARCHAR(100) DEFAULT UUID_STRING(),
TEST_NAME VARCHAR(200),
QUESTION TEXT,
EXPECTED_KEYWORDS ARRAY,
CATEGORY VARCHAR(100),
PRIORITY VARCHAR(20)
);
-- Insert test cases
INSERT INTO RAG_TEST_CASES (TEST_NAME, QUESTION, EXPECTED_KEYWORDS, CATEGORY, PRIORITY)
VALUES
('Basic Connection Test',
'How do I fix connection issues?',
ARRAY_CONSTRUCT('firewall', 'port 443', 'test connection'),
'Troubleshooting',
'HIGH'),
('Pricing Query',
'What does the enterprise plan cost?',
ARRAY_CONSTRUCT('$50', 'unlimited storage', 'enterprise'),
'Pricing',
'HIGH'),
('Security Compliance',
'What security certifications do you have?',
ARRAY_CONSTRUCT('SOC 2', 'GDPR', 'HIPAA', 'encryption'),
'Security',
'HIGH'),
('API Rate Limits',
'What are the API rate limits?',
ARRAY_CONSTRUCT('1000', '5000', 'rate limit', 'enterprise'),
'API Documentation',
'MEDIUM');
-- Run test suite
CREATE OR REPLACE PROCEDURE RUN_RAG_TESTS()
RETURNS TABLE (test_name VARCHAR, passed BOOLEAN, answer TEXT, missing_keywords ARRAY)
LANGUAGE SQL
AS
$$
DECLARE
result_table RESULTSET;
BEGIN
result_table := (
WITH test_results AS (
SELECT
t.TEST_NAME,
t.QUESTION,
t.EXPECTED_KEYWORDS,
ASK_PRODUCT_DOCS(t.QUESTION) as ANSWER
FROM RAG_TEST_CASES t
WHERE t.PRIORITY = 'HIGH'
),
validation AS (
SELECT
TEST_NAME,
ANSWER,
EXPECTED_KEYWORDS,
ARRAY_AGG(keyword) as MISSING_KEYWORDS
FROM test_results,
LATERAL FLATTEN(input => EXPECTED_KEYWORDS) kw
WHERE LOWER(ANSWER) NOT LIKE '%' || LOWER(kw.value::VARCHAR) || '%'
GROUP BY TEST_NAME, ANSWER, EXPECTED_KEYWORDS
)
SELECT
t.TEST_NAME,
CASE
WHEN v.MISSING_KEYWORDS IS NULL THEN TRUE
WHEN ARRAY_SIZE(v.MISSING_KEYWORDS) = 0 THEN TRUE
ELSE FALSE
END as PASSED,
t.ANSWER,
COALESCE(v.MISSING_KEYWORDS, ARRAY_CONSTRUCT()) as MISSING_KEYWORDS
FROM test_results t
LEFT JOIN validation v ON t.TEST_NAME = v.TEST_NAME
);
RETURN TABLE(result_table);
END;
$$;
-- Execute tests
CALL RUN_RAG_TESTS();
Each test case lists keywords the answer must contain. RUN_RAG_TESTS runs the HIGH priority questions through ASK_PRODUCT_DOCS, finds any expected keywords missing from the answer, and returns a pass/fail row per test.
Calling the RAG Function from Applications
Python
import snowflake.connector
def ask_snowflake_rag(question: str) -> str:
conn = snowflake.connector.connect(
user='your_user',
password='your_password',
account='your_account',
warehouse='RAG_WAREHOUSE',
database='RAG_PROJECT',
schema='DOCUMENT_STORE'
)
cursor = conn.cursor()
cursor.execute(
"SELECT ASK_PRODUCT_DOCS(%s)",
(question,)
)
result = cursor.fetchone()[0]
cursor.close()
conn.close()
return result
# Usage
answer = ask_snowflake_rag("How do I reset my password?")
print(answer)
This opens a connection, runs ASK_PRODUCT_DOCS with the question as a bind parameter, and closes the connection. Replace the placeholder credentials with your own, ideally from environment variables or a secrets manager.
The request posts a SQL statement to the /api/v2/statements endpoint with a key-pair JWT. Because the question is inserted directly into the SQL string, a question containing a single quote will break the statement; escape it or use the API’s bind support.
The Node version wraps the callback-based snowflake-sdk in a Promise, binds the question as a parameter, and closes the connection after the query completes.
Advanced Patterns
Multi-language support
One of my favorite projects was a multilingual RAG system. This is the approach:
-- Create multilingual documentation table
CREATE OR REPLACE TABLE PRODUCT_DOCUMENTATION_MULTILANG (
DOC_ID VARCHAR(100),
LANGUAGE VARCHAR(10),
TITLE VARCHAR(500),
CONTENT TEXT,
CATEGORY VARCHAR(100),
ORIGINAL_DOC_ID VARCHAR(100)
);
-- Insert translated versions
INSERT INTO PRODUCT_DOCUMENTATION_MULTILANG
VALUES
(
'DOC001_ES',
'es',
'Comenzando con CloudSync Pro',
'CloudSync Pro es una solución empresarial de sincronización de archivos que permite la colaboración
fluida entre equipos. Para comenzar, primero descargue el cliente de escritorio desde nuestro portal.
Instale la aplicación e inicie sesión con sus credenciales corporativas...',
'Getting Started',
'DOC001'
),
(
'DOC001_FR',
'fr',
'Premiers pas avec CloudSync Pro',
'CloudSync Pro est une solution de synchronisation de fichiers d''entreprise qui permet une
collaboration transparente entre les équipes. Pour commencer, téléchargez d''abord le client
de bureau depuis notre portail...',
'Getting Started',
'DOC001'
);
-- Create language-specific search services
CREATE OR REPLACE CORTEX SEARCH SERVICE PRODUCT_DOCS_SEARCH_ES
ON CONTENT
WAREHOUSE = RAG_WAREHOUSE
TARGET_LAG = '1 hour'
AS (
SELECT
DOC_ID,
CONTENT,
TITLE,
CATEGORY
FROM PRODUCT_DOCUMENTATION_MULTILANG
WHERE LANGUAGE = 'es'
);
-- Create multilingual RAG function
CREATE OR REPLACE FUNCTION ASK_MULTILANG(question VARCHAR, lang VARCHAR)
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
WITH search_results AS (
SELECT
value:content::VARCHAR as content,
value:title::VARCHAR as title
FROM TABLE(
CASE
WHEN lang = 'es' THEN RAG_PROJECT.DOCUMENT_STORE.PRODUCT_DOCS_SEARCH_ES!SEARCH(question, 3)
WHEN lang = 'fr' THEN RAG_PROJECT.DOCUMENT_STORE.PRODUCT_DOCS_SEARCH_FR!SEARCH(question, 3)
ELSE RAG_PROJECT.DOCUMENT_STORE.PRODUCT_DOCS_SEARCH!SEARCH(question, 3)
END
),
LATERAL FLATTEN(input => PARSE_JSON(results))
),
context AS (
SELECT
LISTAGG('Document: ' || title || '\nContent: ' || content, '\n\n---\n\n') as combined_context
FROM search_results
)
SELECT
SNOWFLAKE.CORTEX.COMPLETE(
'mistral-large2',
CONCAT(
CASE
WHEN lang = 'es' THEN 'Eres un asistente útil. Responde en español.'
WHEN lang = 'fr' THEN 'Vous êtes un assistant utile. Répondez en français.'
ELSE 'You are a helpful assistant. Answer in English.'
END,
'\n\nDocumentation:\n',
combined_context,
'\n\nQuestion: ',
question,
'\n\nAnswer:'
)
) as answer
FROM context
$$;
-- Test multilingual queries
SELECT ASK_MULTILANG('¿Cómo soluciono problemas de conexión?', 'es') as spanish_answer;
SELECT ASK_MULTILANG('Comment résoudre les problèmes de connexion?', 'fr') as french_answer;
Translated documents go into one table with a LANGUAGE column, each language gets its own search service, and ASK_MULTILANG picks the service and the answer language from the lang argument. The example only creates the Spanish service; create PRODUCT_DOCS_SEARCH_FR the same way before running the French query.
Tracking performance
-- Create performance tracking table
CREATE OR REPLACE TABLE RAG_PERFORMANCE_METRICS (
METRIC_ID VARCHAR(100) DEFAULT UUID_STRING(),
QUERY_TEXT TEXT,
SEARCH_TIME_MS NUMBER(10,2),
LLM_TIME_MS NUMBER(10,2),
TOTAL_TIME_MS NUMBER(10,2),
DOCS_RETRIEVED NUMBER,
MODEL_USED VARCHAR(50),
SUCCESS BOOLEAN,
ERROR_MESSAGE TEXT,
TIMESTAMP TIMESTAMP_NTZ DEFAULT CURRENT_TIMESTAMP()
);
-- Enhanced function with performance tracking
CREATE OR REPLACE FUNCTION ASK_WITH_METRICS(question VARCHAR)
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
DECLARE
start_time TIMESTAMP_NTZ;
search_start TIMESTAMP_NTZ;
search_end TIMESTAMP_NTZ;
llm_start TIMESTAMP_NTZ;
llm_end TIMESTAMP_NTZ;
result VARCHAR;
BEGIN
start_time := CURRENT_TIMESTAMP();
search_start := CURRENT_TIMESTAMP();
-- Perform search and generate answer
result := ASK_PRODUCT_DOCS(question);
-- Log metrics (simplified version)
INSERT INTO RAG_PERFORMANCE_METRICS (
QUERY_TEXT,
TOTAL_TIME_MS,
MODEL_USED,
SUCCESS
)
VALUES (
question,
DATEDIFF(millisecond, start_time, CURRENT_TIMESTAMP()),
'mistral-large2',
TRUE
);
RETURN result;
END;
$$;
-- Analyze performance
SELECT
DATE_TRUNC('day', TIMESTAMP) as day,
AVG(TOTAL_TIME_MS) as avg_response_time_ms,
PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY TOTAL_TIME_MS) as median_time_ms,
PERCENTILE_CONT(0.95) WITHIN GROUP (ORDER BY TOTAL_TIME_MS) as p95_time_ms,
COUNT(*) as total_queries,
SUM(CASE WHEN SUCCESS THEN 1 ELSE 0 END) as successful_queries
FROM RAG_PERFORMANCE_METRICS
GROUP BY 1
ORDER BY 1 DESC;
ASK_WITH_METRICS calls ASK_PRODUCT_DOCS and records the total time in RAG_PERFORMANCE_METRICS. The search and LLM timing columns are declared but not filled in this simplified version. The final query reports daily average, median and 95th percentile response times.
These were my numbers from production systems:
Average response time: 1.2 to 2.5 seconds
95th percentile: under 4 seconds
Success rate: 99.7%
Cost per query: $0.002 to $0.005
Scaling to millions of documents
For a client with more than 10 million documents, this is what worked:
-- Partition large document sets
CREATE OR REPLACE TABLE PRODUCT_DOCUMENTATION_LARGE (
DOC_ID VARCHAR(100),
TITLE VARCHAR(500),
CONTENT TEXT,
CATEGORY VARCHAR(100),
YEAR NUMBER,
QUARTER NUMBER,
LAST_UPDATED TIMESTAMP_NTZ
)
CLUSTER BY (CATEGORY, YEAR, QUARTER);
-- Create separate search services for different partitions
CREATE OR REPLACE CORTEX SEARCH SERVICE DOCS_SEARCH_CURRENT_YEAR
ON CONTENT
WAREHOUSE = RAG_WAREHOUSE
TARGET_LAG = '30 minutes'
AS (
SELECT
DOC_ID,
CONTENT,
TITLE,
CATEGORY
FROM PRODUCT_DOCUMENTATION_LARGE
WHERE YEAR = YEAR(CURRENT_DATE())
);
CREATE OR REPLACE CORTEX SEARCH SERVICE DOCS_SEARCH_ARCHIVE
ON CONTENT
WAREHOUSE = RAG_WAREHOUSE
TARGET_LAG = '24 hours'
AS (
SELECT
DOC_ID,
CONTENT,
TITLE,
CATEGORY
FROM PRODUCT_DOCUMENTATION_LARGE
WHERE YEAR < YEAR(CURRENT_DATE())
);
-- Smart routing function
CREATE OR REPLACE FUNCTION ASK_LARGE_SCALE(question VARCHAR, prefer_recent BOOLEAN)
RETURNS VARCHAR
LANGUAGE SQL
AS
$$
WITH search_results AS (
SELECT
value:content::VARCHAR as content,
value:title::VARCHAR as title
FROM TABLE(
CASE
WHEN prefer_recent THEN
RAG_PROJECT.DOCUMENT_STORE.DOCS_SEARCH_CURRENT_YEAR!SEARCH(question, 3)
ELSE
RAG_PROJECT.DOCUMENT_STORE.DOCS_SEARCH_ARCHIVE!SEARCH(question, 3)
END
),
LATERAL FLATTEN(input => PARSE_JSON(results))
),
context AS (
SELECT
LISTAGG(
'Document: ' || title || '\n' ||
'Content: ' || content,
'\n\n---\n\n'
) as combined_context
FROM search_results
)
SELECT
SNOWFLAKE.CORTEX.COMPLETE(
'mistral-large2',
CONCAT(
'You are a helpful assistant. Use the documentation to answer:\n\n',
combined_context,
'\n\nQuestion: ',
question,
'\n\nAnswer:'
)
) as answer
FROM context
$$;
The table is clustered by category, year and quarter. Two search services split the data: current-year documents refresh every 30 minutes, archived documents every 24 hours, which cuts refresh work on data that rarely changes. ASK_LARGE_SCALE routes the question to one service or the other based on prefer_recent.
Versioning prompts
To keep the system maintainable as models change:
-- Create version control for prompts
CREATE OR REPLACE TABLE PROMPT_VERSIONS (
VERSION_ID VARCHAR(100) DEFAULT UUID_STRING(),
PROMPT_NAME VARCHAR(200),
PROMPT_TEXT TEXT,
MODEL_NAME VARCHAR(50),
PERFORMANCE_SCORE NUMBER(5,2),
IS_ACTIVE BOOLEAN DEFAULT FALSE,
CREATED_BY VARCHAR(100),
CREATED_AT TIMESTAMP_NTZ DEFAULT CURRENT_TIMESTAMP()
);
-- AB test different prompts
CREATE OR REPLACE PROCEDURE AB_TEST_PROMPTS(question VARCHAR, version_a VARCHAR, version_b VARCHAR)
RETURNS TABLE (version VARCHAR, answer TEXT, user_rating NUMBER)
LANGUAGE SQL
AS
$$
-- Implementation for A/B testing
$$;
PROMPT_VERSIONS stores each prompt with its model and a performance score so you can track which version is active. AB_TEST_PROMPTS is an empty placeholder for your own comparison logic.
What I Recommend After a Year of Building RAG in Snowflake
Start simple, then optimize
Do not over-engineer from day one. Build a basic RAG system first, measure it, then optimize based on real usage.
Document quality beats quantity
I have seen better results from 100 well-written documents than from 1,000 mediocre ones. Time spent making the documentation clear pays off directly in answer quality.
Collect user feedback
-- Create feedback table
CREATE OR REPLACE TABLE USER_FEEDBACK (
FEEDBACK_ID VARCHAR(100) DEFAULT UUID_STRING(),
QUERY_ID VARCHAR(100),
QUESTION TEXT,
ANSWER TEXT,
RATING NUMBER(1,0), -- 1-5 stars
FEEDBACK_TEXT TEXT,
USER_ID VARCHAR(100),
TIMESTAMP TIMESTAMP_NTZ DEFAULT CURRENT_TIMESTAMP()
);
-- Analyze feedback to improve
SELECT
RATING,
COUNT(*) as count,
AVG(LENGTH(ANSWER)) as avg_answer_length,
ARRAY_AGG(QUESTION) as sample_questions
FROM USER_FEEDBACK
GROUP BY RATING
ORDER BY RATING;
The query groups feedback by star rating and shows average answer length and sample questions for each rating, which is a quick way to see what kinds of questions get low scores.
Alert on slow queries
-- Create alert for slow queries
CREATE OR REPLACE ALERT SLOW_QUERIES_ALERT
WAREHOUSE = RAG_WAREHOUSE
SCHEDULE = '60 MINUTE'
IF (EXISTS (
SELECT 1
FROM RAG_PERFORMANCE_METRICS
WHERE TIMESTAMP > DATEADD(hour, -1, CURRENT_TIMESTAMP())
AND TOTAL_TIME_MS > 5000
HAVING COUNT(*) > 10
))
THEN CALL SYSTEM$SEND_EMAIL(
'[email protected]',
'RAG System Alert: High Latency Detected',
'Multiple slow queries detected in the last hour'
);
The alert runs hourly and sends an email if more than 10 queries in the last hour took over 5 seconds. Change the recipient address and thresholds to suit your system.
Revisit your prompts
As models improve, revisit your prompts. What worked with an older model might not be the best choice for a newer one.
Final thoughts
Building RAG in Snowflake has been one of the most rewarding projects of my career. Running production AI workloads in a data warehouse seemed impossible to me a year earlier, and now it is practical. Cortex Search removes the usual barriers: no separate vector database, no embedding pipeline, no synchronization problems. Just SQL and your data.
I’ve used variations of these patterns in systems handling millions of queries per month. If you are starting out:
Start small with a single table of documents.
Test using the test case approach above.
Measure performance, cost and user satisfaction.
Iterate quickly rather than waiting for perfection.
Listen to users; their feedback will tell you what to fix.
Modern data architectures are evolving rapidly, and Snowflake Cortex AISQL is at the forefront of this change. It lets you query unstructured data—files, images, and text—directly using SQL enhanced with AI capabilities. But here’s the catch: these powerful AI features come with significant computational overhead. If you’re not careful about optimization, you’ll face slow queries and skyrocketing costs.
This guide walks you through practical strategies to get the most out of Cortex AISQL while keeping your warehouse credits in check.
Why Snowflake Cortex AISQL Query Optimization Matters in 2025
The amount of unstructured data in cloud warehouses has exploded. Cortex AISQL makes it easier for developers to work with this data without needing deep data science expertise. That’s great for democratizing AI, but it also puts serious strain on your computational resources.
Here’s what happens when you neglect optimization:
Costs spiral out of control – Poorly optimized queries can unexpectedly spike your cloud computing bills
Slow results hurt decision-making – Business users need timely insights, not queries that take minutes to complete
Limited concurrency – Inefficient queries hog resources, preventing other users from accessing AI insights
The good news? With proper optimization, you can protect your budget, improve performance, and enable more users to leverage AI across your organization.
Understanding How Cortex AISQL Works
Cortex AISQL translates your SQL statements into complex workflows that involve AI models. When you run a query, Snowflake:
Parses your request and identifies which AI functions to call (like CORTEX_ANALYST or embedding generation)
Determines the optimal execution plan, balancing data retrieval with external model calls
Executes the query across both storage and compute layers
The key to optimization is minimizing data movement and reducing the amount of data sent to the AI processing layer. Think of it like this: every row you can filter out before calling an AI function is money and time saved.
Getting Started: Profile Your Queries First
Before you start optimizing, you need to understand where your bottlenecks are. Use Snowflake’s Query Profile feature to identify:
Steps that consume the most time
External function calls that are slowing things down
Massive table scans that could be avoided
Here’s a real example of what NOT to do:
-- ❌ BAD: Passing all documents to the AI function
SELECT
document_id,
CORTEX_ANALYST(document_text, 'Summarize key themes') AS summary
FROM
large_documents;
This query sends every single document through the AI function. If you have millions of documents, you’re looking at a very expensive (and slow) operation.
The Single Most Effective Optimization: Filter Early, Filter Hard
The best way to optimize AISQL queries is brutally simple: reduce your data before calling AI functions. Use standard SQL filtering to narrow down your dataset first.
Here’s the improved version:
-- ✅ GOOD: Filter aggressively before using AI functions
SELECT
d.document_id,
d.document_name,
CORTEX_ANALYST(d.document_text, 'Summarize key themes') AS summary
FROM
large_documents d
INNER JOIN
document_metadata m ON d.document_id = m.document_id
WHERE
m.created_date >= DATEADD(month, -1, CURRENT_DATE())
AND m.category = 'Financial Reports'
AND m.status = 'Published'
AND d.document_text IS NOT NULL
LIMIT 500;
This query only processes recent financial reports that are published and have actual text content. We’ve potentially reduced the dataset from millions to hundreds of rows before the expensive AI operation runs.
Smart Join Strategies
Joins can make or break your AISQL performance. Here’s what works:
Prioritize inner joins over outer joins – They reduce your result set immediately:
-- ✅ GOOD: Inner join reduces data early
SELECT
c.customer_id,
c.feedback_text,
CORTEX_SENTIMENT(c.feedback_text) AS sentiment_score
FROM
customer_feedback c
INNER JOIN
active_customers a ON c.customer_id = a.customer_id
WHERE
c.feedback_date >= '2025-01-01'
AND a.subscription_status = 'Active';
Filter out test data explicitly – Don’t let test accounts pollute your AI analysis:
-- ✅ GOOD: Exclude test accounts
SELECT
email,
message_content,
CORTEX_ANALYST(message_content, 'Extract action items') AS actions
FROM
support_messages
WHERE
email NOT LIKE '%@test.com'
AND email NOT LIKE '%test%@%'
AND user_type = 'Production'
AND created_date >= DATEADD(week, -2, CURRENT_DATE());
Pre-Calculate and Store Embeddings
If you’re doing semantic search or similarity matching, generating embeddings on the fly is expensive. Instead, calculate them once and store them:
-- Step 1: Create a table with pre-calculated embeddings
CREATE TABLE product_descriptions_with_embeddings AS
SELECT
product_id,
description,
CORTEX_EMBED_TEXT('e5-base-v2', description) AS description_embedding
FROM
products
WHERE
description IS NOT NULL;
-- Step 2: Use the pre-calculated embeddings for fast similarity search
SELECT
product_id,
description,
VECTOR_COSINE_SIMILARITY(
description_embedding,
CORTEX_EMBED_TEXT('e5-base-v2', 'wireless headphones')
) AS similarity_score
FROM
product_descriptions_with_embeddings
ORDER BY
similarity_score DESC
LIMIT 20;
This approach transforms an expensive embedding calculation into a fast lookup. The difference can be dramatic—queries that took minutes might now run in seconds.
Optimize Your Table Structure
Set up clustering keys that align with your most common query patterns:
-- Cluster by fields you frequently filter on
ALTER TABLE customer_documents
CLUSTER BY (document_type, created_month);
-- Now queries filtering by these fields run much faster
SELECT
document_id,
CORTEX_ANALYST(document_content, 'Extract key dates') AS key_dates
FROM
customer_documents
WHERE
document_type = 'Contract'
AND created_month >= '2025-01-01';
Size Your Warehouse Appropriately
AI workloads need more compute power than traditional SQL queries. Don’t be afraid to scale up:
-- Configure a dedicated warehouse for AI workloads
CREATE WAREHOUSE AI_ANALYSIS_WH WITH
WAREHOUSE_SIZE = 'LARGE'
AUTO_SUSPEND = 120
AUTO_RESUME = TRUE
INITIALLY_SUSPENDED = TRUE
STATEMENT_TIMEOUT_IN_SECONDS = 7200;
-- Use it for your Cortex queries
USE WAREHOUSE AI_ANALYSIS_WH;
Start with a LARGE warehouse for AI tasks. You can always scale down if it’s overkill, but starting too small will frustrate users and mask optimization opportunities.
Common Mistakes to Avoid
#1: Using AI functions inside loops or repeated operations
-- ❌ BAD: Calling AI function for each row unnecessarily
SELECT
product_id,
(SELECT CORTEX_ANALYST(description, 'Extract features')
FROM products p2
WHERE p2.product_id = p1.product_id) AS features
FROM
products p1;
Mistake #2: Not checking for NULL values
-- ❌ BAD: Wasting AI calls on empty data
SELECT
CORTEX_ANALYST(user_comment, 'Analyze sentiment')
FROM
feedback;
-- ✅ GOOD: Filter out NULLs first
SELECT
CORTEX_ANALYST(user_comment, 'Analyze sentiment')
FROM
feedback
WHERE
user_comment IS NOT NULL
AND LENGTH(user_comment) > 10;
Mistake #3: Ignoring warehouse resource monitors
Set up resource monitors to prevent runaway queries from draining your credits:
CREATE RESOURCE MONITOR ai_workload_monitor WITH
CREDIT_QUOTA = 1000
TRIGGERS
ON 75 PERCENT DO NOTIFY
ON 90 PERCENT DO SUSPEND
ON 100 PERCENT DO SUSPEND_IMMEDIATE;
ALTER WAREHOUSE AI_ANALYSIS_WH
SET RESOURCE_MONITOR = ai_workload_monitor;
Monitoring and Maintaining Performance
Don’t set it and forget it. Regularly review:
Query execution times – Are they trending up?
Credit consumption – Any unexpected spikes?
Warehouse queuing – Are queries waiting too long to start?
Use Snowflake’s Query History to track these metrics:
-- Find your most expensive AISQL queries
SELECT
query_text,
execution_time,
credits_used_cloud_services,
warehouse_name
FROM
SNOWFLAKE.ACCOUNT_USAGE.QUERY_HISTORY
WHERE
query_text ILIKE '%CORTEX%'
AND start_time >= DATEADD(day, -7, CURRENT_DATE())
ORDER BY
execution_time DESC
LIMIT 20;
Putting It All Together: A Real-World Example
Let’s say you need to analyze customer support tickets to identify trends. Here’s how to do it efficiently:
-- Create a materialized view for frequently accessed metadata
CREATE MATERIALIZED VIEW support_ticket_summary AS
SELECT
ticket_id,
customer_id,
category,
priority,
created_date,
status
FROM
support_tickets
WHERE
created_date >= DATEADD(year, -1, CURRENT_DATE());
-- Now run your AI analysis efficiently
SELECT
s.ticket_id,
s.category,
s.priority,
CORTEX_ANALYST(t.ticket_description,
'Extract: 1) main issue, 2) customer sentiment, 3) urgency level'
) AS ai_analysis
FROM
support_ticket_summary s
INNER JOIN
support_ticket_text t ON s.ticket_id = t.ticket_id
WHERE
s.created_date >= DATEADD(week, -1, CURRENT_DATE())
AND s.category = 'Technical'
AND s.priority IN ('High', 'Critical')
AND s.status = 'Open'
AND t.ticket_description IS NOT NULL
LIMIT 1000;
This query:
Uses a materialized view for fast metadata access
Filters early on date, category, priority, and status
Checks for NULL values before calling the AI function
Limits results to a reasonable number
Key Takeaways
Optimizing Cortex AISQL queries isn’t rocket science, but it does require discipline:
Filter aggressively before calling AI functions
Pre-calculate embeddings for repeated use
Use appropriate warehouse sizes for AI workloads
Set up clustering keys aligned with your query patterns
Monitor performance regularly and adjust as needed
Exclude test data explicitly from production queries
The combination of traditional Snowflake optimization techniques with AI-specific strategies will give you fast queries and manageable costs. Start with these fundamentals, measure the impact, and iterate from there.
The first time I ran APPROX_TOP_K on a 2-billion-row events table, the query finished in under four seconds. The equivalent GROUP BY / ORDER BY / LIMIT had been timing out at 8 minutes. Same result. Ninety-eight percent the same result, to be precise — but for top-10 product rankings, that margin was irrelevant.
That’s the pattern with Snowflake’s lesser-known aggregation functions: they’re not novelties, and they’re not edge cases for data scientists. They solve real, recurring problems — frequency estimation at scale, distribution analysis, Jaccard similarity across user sets — that the standard SUM/COUNT/AVG toolkit either can’t handle or handles slowly and expensively.
This article covers six of them. Each section includes the practical use case, the SQL, the output, and a note on where I’ve seen it matter — or where I initially got it wrong.
1. APPROX_TOP_K — Frequency Estimation Without GROUP BY Pain
APPROX_TOP_K · APPROX_TOP_K_ARRAY
When you need the top-N most frequent values in a large dataset, a naive GROUP BY ... ORDER BY COUNT(*) DESC LIMIT N forces a full sort of the aggregated result. On hundreds of millions of rows that’s slow, memory-intensive, and often unnecessary — because you don’t need exact counts, you need the right top items.
APPROX_TOP_K uses a space-efficient sketch (the Space-Saving algorithm) to identify the most frequent values with high confidence and a fraction of the compute. The accuracy is configurable. The default counter size gives you the top-K items with at most a small error margin, and in practice I’ve never seen it return a wrong top-10 on real sales or event data.
One thing that tripped me up early: APPROX_TOP_K returns a single JSON object, while APPROX_TOP_K_ARRAY returns an array of JSON objects. If you’re piping the result into a downstream process or flattening it with LATERAL FLATTEN, use the array variant.
-- APPROX_TOP_K_ARRAY: top 3 most sold products
-- Works correctly on tables with billions of rows where GROUP BY times out
WITH top_k AS (
SELECT APPROX_TOP_K(product_group, 3) AS arr
FROM SNOWDQ_DB.PUBLIC.SALES_DATA
)
SELECT f.value[0]::STRING AS product_group,
f.value[1]::INT AS approx_count
FROM top_k, LATERAL FLATTEN(INPUT => top_k.arr) f;
The accuracy guarantee: APPROX_TOP_K can report a false positive — an item that’s not truly in the top K — only if its actual frequency is greater than n/(K + error_rate). In practice on typical sales or click data, the result is reliable for any K ≤ 100.
2. MODE — The Aggregation You’ve Been Writing Manually
MODE()
Before I knew MODE() existed, I was writing this every time I needed the most common value per group:
-- The manual way — verbose and slower
SELECT region, payment_method
FROM (
SELECT region, payment_method,
ROW_NUMBER() OVER (PARTITION BY region ORDER BY COUNT(*) DESC) AS rn
FROM transactions
GROUP BY region, payment_method
)
WHERE rn = 1;
That works, but it’s a subquery with a window function over an aggregation. MODE() does the same job in a single line:
WITH transactions(region, payment_method) AS (
SELECT * FROM VALUES ('North','Credit Card'),('North','Credit Card'),('North','Cash'),
('South','Cash'),('South','Cash'),('South','PayPal'),('East','PayPal'),('East','PayPal'),('East','Cash')
),
manual AS (
SELECT region, payment_method FROM (
SELECT region, payment_method,
ROW_NUMBER() OVER (PARTITION BY region ORDER BY COUNT(*) DESC) AS rn
FROM transactions GROUP BY region, payment_method) WHERE rn = 1
),
m AS (SELECT region, MODE(payment_method) AS most_common_payment FROM transactions GROUP BY region)
SELECT m.region, m.most_common_payment, manual.payment_method AS manual_result
FROM m JOIN manual USING (region) ORDER BY region
The one behaviour to be aware of: when there’s a tie — two values with equal frequency — MODE returns one of them non-deterministically. If tie-breaking matters to your use case, you’ll need to fall back to the ROW_NUMBER pattern with an explicit tiebreaker in the ORDER BY. But for dashboards, feature engineering, and exploratory analysis, MODE is far cleaner.
3. ARRAY_AGG and ARRAY_UNIQUE_AGG: Turning Rows into ArraysARRAY_AGG() · ARRAY_UNIQUE_AGG()
These are among the most useful Snowflake functions for denormalization work. Use them anywhere you need to roll related values up into a single array column. ARRAY_AGG keeps duplicates, and adding WITHIN GROUP (ORDER BY ...) controls the order of the array. ARRAY_UNIQUE_AGG returns distinct values only. Use ARRAY_AGG when you want the full purchase history, including repeat purchases. Use ARRAY_UNIQUE_AGG when you want the distinct set of products a customer has ever bought.
Coming from Spark or Hive?COLLECT_LIST maps to ARRAY_AGG, and COLLECT_SET maps to ARRAY_UNIQUE_AGG. Snowflake didn’t recognize the Spark names when I tested them.
SELECT
customer_id,
ARRAY_AGG(product_name) WITHIN GROUP (ORDER BY sale_date) AS full_purchase_history, -- includes dupes
ARRAY_UNIQUE_AGG(product_name) AS distinct_products_bought -- unique only
FROM sales_data
GROUP BY customer_id
ORDER BY customer_id;
Where I use this most: building ML feature tables where one column needs to represent a user’s interaction history as a variable-length sequence, and in customer 360 pipelines where you want to denormalize order line items back up to the customer level before writing to a serving layer.
4.SKEW and KURTOSIS: Distribution Diagnostics Without Leaving SQLSKEW() · KURTOSIS()
When data engineers want to know whether a numeric column is lopsided or full of outliers, most export it to Python or open a BI tool. Snowflake can answer that in SQL, so you can run distribution checks inside a dbt model or a data quality test without switching tools.
SKEW measures asymmetry. A positive value means a long right tail: a few very high values pull the mean up, which is typical of price data with luxury outliers. A negative value means the tail is on the left. A value near 0 means the distribution is roughly symmetric.
KURTOSIS measures how heavy the tails are. Snowflake returns excess kurtosis, so a normal distribution scores about 0. Tools that report raw kurtosis put a normal distribution at about 3. Positive values mean more extreme outliers than a normal distribution would produce.
Example Use Case: Analyzing Price Distribution
-- Distribution diagnostics on product prices
SELECT
COUNT(price_usd) AS n,
SKEW(price_usd) AS price_skewness,
KURTOSIS(price_usd) AS price_excess_kurtosis -- normal ≈ 0
FROM product_prices;
-- Sample output: seven prices between $10 and $13, plus one $100 outlier
-- N | PRICE_SKEWNESS | PRICE_EXCESS_KURTOSIS
-- --|----------------|----------------------
-- 7 | 2.64 | 6.98
The single $100 outlier creates strong positive skew and heavy tails. That’s a signal to investigate before you feed this column into an ML model.
A caveat about thresholds: kurtosis depends on row count. The same single outlier scored about 5 in a 5-row table, about 7 in a 7-row table, and about 10 in a 10-row table. A fixed rule like “investigate if kurtosis is above 10” can miss problems in small tables and raise too many alarms in large ones. Read the number next to COUNT(), and confirm what you see with MIN, MAX, or APPROX_PERCENTILE before deciding how to handle outliers.
Both functions ignore NULLs, and on very small inputs they can return NULL.
4. HLL_ACCUMULATE — Counting Distinct Values at Billion-Row Scale
HLL_ACCUMULATE() · HLL_COMBINE() · HLL_ESTIMATE()
This is the one I wish more people knew about. COUNT(DISTINCT ...) in Snowflake is exact but expensive — it requires keeping track of every unique value seen, which blows up memory on very large cardinalities. HyperLogLog (HLL_ACCUMULATE) gives you an approximate distinct count using a fixed-size sketch, regardless of how many unique values there are.
The practical accuracy is within 1–2% of the true count in almost all cases. On a table with 500 million rows and 40 million distinct user IDs, the HLL sketch runs in seconds; COUNT(DISTINCT user_id) takes minutes.
SELECT
DATE_TRUNC('day', event_time) AS event_day,
HLL_ESTIMATE(HLL_ACCUMULATE(user_id)) AS approx_distinct_users
FROM user_events
GROUP BY 1
ORDER BY 1 DESC;
-- The real power: combine sketches across time windows without re-scanning
-- "How many distinct users across the last 7 days combined?"
SELECT
HLL_ESTIMATE(
HLL_COMBINE(
ARRAY_AGG(daily_sketch)
)
) AS distinct_users_last_7d
FROM (
SELECT HLL_ACCUMULATE(user_id) AS daily_sketch
FROM user_events
WHERE event_time >= CURRENT_DATE - 7
GROUP BY DATE_TRUNC('day', event_time)
) daily_sketches;
The HLL_COMBINE step is what makes this especially powerful for incremental pipelines: you can pre-compute daily HLL sketches, store them, and merge them at query time without ever re-scanning the raw event table. This is the same technique web analytics platforms use to report 28-day unique visitor counts instantly.
MINHASH and APPROXIMATE_SIMILARITY — Jaccard Similarity Without Cross Joins
MINHASH() · APPROXIMATE_SIMILARITY()
The last one is genuinely rare to see in the wild, and it solves a problem that traditionally required either a self-join or a Python job to handle. MINHASH computes a probabilistic sketch of a set, and APPROXIMATE_SIMILARITY takes two of those sketches and returns the estimated Jaccard similarity — the fraction of items the two sets have in common.
Where this matters: customer segment overlap analysis, duplicate detection across product catalogs, comparing which users two marketing campaigns reached, or detecting near-duplicate content. The traditional approach is a cross join on set membership, which is O(n²) and completely impractical above a few thousand rows.
-- MINHASH + APPROXIMATE_SIMILARITY: Jaccard similarity between two customer segments
-- No cross join required
WITH segment_sketches AS (
SELECT
campaign_id,
MINHASH(100, customer_id) AS customer_sketch -- 100 hash functions = good accuracy
FROM campaign_members
GROUP BY campaign_id
)
SELECT
a.campaign_id AS campaign_a,
b.campaign_id AS campaign_b,
APPROXIMATE_SIMILARITY(a.customer_sketch, b.customer_sketch) AS jaccard_similarity
FROM segment_sketches a
JOIN segment_sketches b ON a.campaign_id < b.campaign_id
ORDER BY jaccard_similarity DESC;
-- Output example:
-- CAMPAIGN_A | CAMPAIGN_B | JACCARD_SIMILARITY
-- -----------|------------|-------------------
-- spring_24 | summer_24 | 0.71
-- summer_24 | fall_24 | 0.43
-- spring_24 | fall_24 | 0.29
A similarity of 0.71 between spring and summer campaigns means 71% of the customers they reached were the same people — which is useful to know before running both again. I’ve used this exact pattern for a media client to detect ad campaign overlap before recommending budget reallocation. The query ran in under 30 seconds on a 50-million-row membership table. The equivalent Python job had been taking 40 minutes.
Which Function for Which Problem
Quick reference for the next time one of these problems comes up:
APPROX_TOP_K — Top-N most frequent values on huge tables where GROUP BY is too slow
MODE() — Most common value per group, in one line instead of a subquery
ARRAY_AGG and ARRAY_UNIQUE_AGG — Aggregate row values into arrays for ML features or 360 views
SKEW / KURTOSIS — Distribution shape diagnostics without leaving SQL
HLL_ACCUMULATE — Approximate distinct counts at scale; combinable across time windows
MINHASH / APPROXIMATE_SIMILARITY — Set similarity without cross joins
All six are available on every Snowflake edition. None require any special configuration. The only cost is the warehouse time to run the query — and in most cases that cost is substantially lower than the standard alternative, which is the point.