🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Snowflake Materialized Views

đŸŸĸ Free Lesson

Snowflake Materialized Views

Materialized views in Snowflake store pre-computed results of query expressions, dramatically improving performance for complex, frequently-executed queries.

Materialized View ArchitectureBase Tables(Source Data)Incremental RefreshMaterialized View(Pre-computed)Serve QueriesQuery Engine(Auto-Rewrite)Optimizer(Match Patterns)RewriteMatchAutomatic | Incremental | No manual refresh needed

Architecture Diagram 2: Materialized View Refresh Cycle

Materialized View Incremental Refresh CycleBase TableINSERT/UPDATENew data arrivesDetect ChangesTrack deltasIdentify affected rowsIncremental ComputeRe-aggregate onlyChanged partitionsUpdated MVFresh resultsQuery instantlyAutomatic | Incremental | No manual refresh needed | Background task

Creating Materialized Views

Basic Syntax

-- Simple materialized view
CREATE MATERIALIZED VIEW mv_daily_sales AS
SELECT
  order_date,
  COUNT(*) AS order_count,
  SUM(amount) AS total_sales,
  AVG(amount) AS avg_sale
FROM orders
GROUP BY order_date;

-- Materialized view with JOIN
CREATE MATERIALIZED VIEW mv_customer_orders AS
SELECT
  c.customer_id,
  c.customer_name,
  COUNT(o.order_id) AS order_count,
  SUM(o.amount) AS total_spent
FROM customers c
LEFT JOIN orders o ON c.customer_id = o.customer_id
GROUP BY c.customer_id, c.customer_name;

Advanced Materialized Views

-- Materialized view with filtering
CREATE MATERIALIZED VIEW mv_high_value_orders AS
SELECT
  customer_id,
  COUNT(*) AS order_count,
  SUM(amount) AS total_amount
FROM orders
WHERE amount > 1000
GROUP BY customer_id;

-- Materialized view with window functions
CREATE MATERIALIZED VIEW mv_customer_ranking AS
SELECT
  customer_id,
  SUM(amount) AS total_spent,
  RANK() OVER (ORDER BY SUM(amount) DESC) AS spending_rank
FROM orders
GROUP BY customer_id;

How Materialized Views Work

Incremental Refresh

-- Check refresh status
SELECT
  name,
  refresh_state,
  last_refresh_time,
  refresh_error
FROM INFORMATION_SCHEMA.MATERIALIZED_VIEWS
WHERE name = 'MV_DAILY_SALES';

-- Manual refresh (if needed)
ALTER MATERIALIZED VIEW mv_daily_sales REFRESH;

Automatic Query Rewrite

-- This query automatically uses the materialized view
SELECT
  order_date,
  COUNT(*) AS order_count,
  SUM(amount) AS total_sales
FROM orders
GROUP BY order_date;

-- Snowflake rewrites this to use mv_daily_sales
EXPLAIN SELECT
  order_date,
  COUNT(*) AS order_count,
  SUM(amount) AS total_sales
FROM orders
GROUP BY order_date;

Materialized View Limitations

RestrictionDescription
No JOINs (with exceptions)Limited JOIN support
No UNIONCannot use UNION operations
No DISTINCTDISTINCT not supported
No LIMITLIMIT clause not allowed
No SubqueriesSubqueries in SELECT not allowed
GROUP BY RequiredMust have GROUP BY clause
-- Valid materialized view patterns
CREATE MATERIALIZED VIEW mv_valid AS
SELECT
  column1,
  AGG_FUNC(column2) AS agg_result
FROM base_table
GROUP BY column1;

-- Invalid patterns (will fail)
-- SELECT DISTINCT column1 FROM base_table;
-- SELECT * FROM base_table LIMIT 10;
-- SELECT column1, (SELECT MAX(x) FROM t2) FROM base_table;

Performance Monitoring

-- Check materialized view size and refresh stats
SELECT
  mv.name,
  mv.table_schema,
  mv.data_retention_time_in_days,
  ts.table_size_bytes,
  ts.total_rows,
  mv.last_refresh_time
FROM INFORMATION_SCHEMA.MATERIALIZED_VIEWS mv
JOIN INFORMATION_SCHEMA.TABLE_STORAGE_METRICS ts
  ON mv.name = ts.table_name
WHERE mv.name = 'MV_DAILY_SALES';

-- Monitor query rewrite usage
SELECT
  query_id,
  query_text,
  credits_used
FROM TABLE(INFORMATION_SCHEMA.QUERY_HISTORY(
  START_TIME => DATEADD('day', -1, CURRENT_TIMESTAMP())
))
WHERE query_text LIKE '%MV_DAILY_SALES%';

Drop Rules

-- Check drop rules for materialized views
SELECT
  name,
  drop_rule,
  source_table
FROM INFORMATION_SCHEMA.MATERIALIZED_VIEW_REFRESH_HISTORY
WHERE name = 'MV_DAILY_SALES';

-- Force refresh to check drop rules
ALTER MATERIALIZED VIEW mv_daily_sales REFRESH;

Best Practices

PracticeRecommendationBenefit
Simple AggregationsUse COUNT, SUM, AVGEfficient refresh
Time-based GroupingGROUP BY date/hourNatural partitioning
Filter EarlyWHERE clause in MVReduced data processed
Monitor RefreshCheck refresh_historyEarly issue detection
Size AppropriatelyBalance storage vs performanceCost optimization
-- Recommended: Simple aggregation with time grouping
CREATE MATERIALIZED VIEW mv_hourly_metrics AS
SELECT
  DATE_TRUNC('hour', event_time) AS event_hour,
  event_type,
  COUNT(*) AS event_count,
  COUNT(DISTINCT user_id) AS unique_users
FROM events
GROUP BY 1, 2;

-- Monitor refresh performance
SELECT
  name,
  refresh_start_time,
  refresh_end_time,
  TIMESTAMPDIFF('second', refresh_start_time, refresh_end_time) AS duration_seconds
FROM INFORMATION_SCHEMA.MATERIALIZED_VIEW_REFRESH_HISTORY
WHERE name = 'MV_HOURLY_METRICS'
ORDER BY refresh_start_time DESC
LIMIT 5;

Summary

Key Takeaways

Materialized views store pre-computed query results for instant access without re-execution.

Incremental refresh maintains data freshness automatically as base tables change.

Query optimizer transparently rewrites queries to use materialized views — no code changes needed.


When to Use Materialized Views

ScenarioRecommendation
Frequent aggregation queriesUse Materialized Views
Real-time dashboardsConsider regular Views instead
Complex JOINs with GROUP BYMV with simple aggregations
Ad-hoc queriesRegular Views or tables
Heavy compute queriesMV for pre-computation

Limitations to Remember

  1. No DISTINCT operations allowed
  2. No LIMIT clause permitted
  3. No subqueries in SELECT list
  4. GROUP BY clause is required
  5. Limited JOIN support (not all patterns supported)

See Also


Extended Learning: Beyond the Basics

Key Concepts Summary

This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.

Prerequisite Knowledge

Before studying this topic in depth, ensure you understand:

  • Basic definitions and terminology
  • Core formulas and their derivations
  • Common applications in real-world scenarios
  • Typical pitfalls and misconceptions

Step-by-Step Walkthrough

Let us work through a complete example to solidify understanding:

Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.

Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.

Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.

Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.

Common Mistakes to Avoid

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. Forgetting constraints — Check that solutions satisfy all given conditions

Real-World Applications

Understanding this concept is essential for:

  • Advanced problem solving in examinations
  • Building intuition for more complex topics
  • Developing analytical thinking skills
  • Applying mathematical reasoning to practical situations

Practice Exercises

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. Challenge: Create your own problem that requires this concept plus additional knowledge.

Interview and Exam Tips

  • Common question patterns: Identify which exam or interview formats test this topic
  • Time management: Practice completing problems within time constraints
  • Common traps: Know the typical mistakes examiners set as distractors
  • Verification strategy: Develop a quick method to check your answer

Related Topics

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids errors

Further Reading

For students who want to go deeper:

  • Standard textbooks on the subject
  • Research papers applying this concept
  • Online courses with video explanations
  • Practice problem collections with detailed solutions
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Snowflake Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement