Snowflake Query History and Optimization
Query History provides comprehensive visibility into all queries executed in Snowflake, enabling performance analysis, cost optimization, and troubleshooting.
What is Query History?
- Tracks all queries with execution metadata
- Retains data for 365 days (Enterprise) or 7 days (Standard)
- Enables profiling, cost analysis, and optimization
Architecture Overview
The query history and optimization architecture includes four components:
- Query Execution Pipeline â Parse â Optimize â Compile â Execute â Fetch â Result Cache
- Query History Metadata â Execution time, bytes scanned, partitions, spillage, cost
- Optimization Tools â Query profile, execution plan, result cache, clustering keys, materialized views
- Best Practices â Use clustering keys, limit data scanning, optimize warehouse size, monitor spillage, use result caching
Query History Access
Basic Query History
-- Recent queries
SELECT
query_id,
query_text,
user_name,
start_time,
end_time,
total_elapsed_time as duration_ms,
bytes_scanned,
rows_produced,
warehouse_name
FROM TABLE(INFORMATION_SCHEMA.QUERY_HISTORY(
START_TIME => DATEADD(hour, -24, CURRENT_TIMESTAMP()),
END_TIME => CURRENT_TIMESTAMP()
))
ORDER BY start_time DESC;
-- Specific user queries
SELECT * FROM TABLE(INFORMATION_SCHEMA.QUERY_HISTORY(
USER_NAME => 'analyst@company.com',
START_TIME => DATEADD(day, -7, CURRENT_TIMESTAMP())
));
Query Profile
-- Enable query profile
ALTER SESSION SET ENABLE_QUERY_PROFILE = TRUE;
-- Run query and check profile
SELECT * FROM large_table WHERE id = 123;
-- View profile
SELECT *
FROM TABLE(INFORMATION_SCHEMA.QUERY_PROFILE(
QUERY_ID => LAST_QUERY_ID()
));
Performance Analysis
Top Expensive Queries
-- Find queries with most bytes scanned
SELECT
query_text,
total_elapsed_time,
bytes_scanned / 1024 / 1024 / 1024 as gb_scanned,
rows_produced,
warehouse_name,
compilation_time,
execution_time,
queue_time
FROM TABLE(INFORMATION_SCHEMA.QUERY_HISTORY(
START_TIME => DATEADD(day, -7, CURRENT_TIMESTAMP())
))
WHERE bytes_scanned > 1024 * 1024 * 1024
ORDER BY bytes_scanned DESC
LIMIT 20;
Warehouse Utilization
-- Warehouse usage statistics
SELECT
warehouse_name,
COUNT(*) as query_count,
AVG(total_elapsed_time) as avg_duration_ms,
SUM(bytes_scanned) / 1024 / 1024 / 1024 as total_gb_scanned,
SUM(credits_used) as total_credits
FROM TABLE(INFORMATION_SCHEMA.QUERY_HISTORY(
START_TIME => DATEADD(day, -30, CURRENT_TIMESTAMP())
))
GROUP BY 1
ORDER BY total_gb_scanned DESC;
Query Optimization Techniques
Clustering Key Analysis
-- Check clustering depth
SELECT
SYSTEM$CLUSTERING_DEPTH('database.schema.table');
-- Check clustering information
SELECT *
FROM TABLE(INFORMATION_SCHEMA.CLUSTERING_TABLE_INFO(
'database.schema.table'
));
-- Recommend clustering key
SELECT *
FROM TABLE(INFORMATION_SCHEMA.CLUSTERING_RECOMMENDATIONS(
'database.schema.table'
));
Result Cache Hit Rate
-- Cache performance
SELECT
COUNT(*) as total_queries,
SUM(CASE WHEN query_id IN (
SELECT query_id FROM TABLE(INFORMATION_SCHEMA.QUERY_HISTORY())
WHERE execution_status = 'SUCCESS'
AND total_elapsed_time < 100
) THEN 1 ELSE 0 END) as cached_queries,
(cached_queries / total_queries * 100) as cache_hit_rate
FROM TABLE(INFORMATION_SCHEMA.QUERY_HISTORY(
START_TIME => DATEADD(day, -7, CURRENT_TIMESTAMP())
));
Cost Analysis
-- Credit consumption by query type
SELECT
CASE
WHEN query_text LIKE '%SELECT%' THEN 'SELECT'
WHEN query_text LIKE '%INSERT%' THEN 'INSERT'
WHEN query_text LIKE '%UPDATE%' THEN 'UPDATE'
WHEN query_text LIKE '%DELETE%' THEN 'DELETE'
WHEN query_text LIKE '%COPY%' THEN 'COPY'
ELSE 'Other'
END as query_type,
COUNT(*) as query_count,
SUM(credits_used) as total_credits,
AVG(credits_used) as avg_credits
FROM TABLE(INFORMATION_SCHEMA.QUERY_HISTORY(
START_TIME => DATEADD(day, -30, CURRENT_TIMESTAMP())
))
GROUP BY 1
ORDER BY total_credits DESC;
See Also
- Monitoring Queries â Set up alerts for data quality and performance issues
- Optimization â Improve performance with materialized views and caching
- Access History â Track who accessed which data for compliance
Deep Dive: Practical Implementation
Architecture Patterns
| Pattern | Description | Use Case | Complexity |
|---|---|---|---|
| Lambda Architecture | Batch + serving layers | Historical + real-time | High |
| Kappa Architecture | Streaming-only | Real-time analytics | Medium |
| Micro-batch Architecture | Small batch processing | Near-real-time | Low-Medium |
| CDC-based | Change data capture | Incremental loads | Medium |
Production Checklist
- Implement idempotent pipeline operations
- Add dead-letter queues for failed records
- Set up comprehensive monitoring and alerting
- Configure automated backups and disaster recovery
- Document data lineage and dependencies
- Implement role-based access control
- Set up cost monitoring and budget alerts
- Create runbooks for common failure scenarios
- Establish SLA monitoring for data freshness
- Conduct regular security audits and penetration testing
Common Pitfalls
- Not handling schema evolution â Use schema registries and backward-compatible changes
- Ignoring data skew â Monitor distribution and rebalance when needed
- Over-orchestrating â Use simpler tools when they suffice
- No data quality checks â Implement validation at every stage
- Skipping documentation â Data catalogs prevent discovery chaos
- Not monitoring costs â Cloud costs can spiral without oversight
- Tight coupling â Design for loose coupling between components
- No testing strategy â Unit, integration, and data quality tests are essential
Interview Preparation
Q: How do you debug a failing pipeline? A: Check logs for errors, verify source data availability, inspect intermediate outputs, check resource utilization, review recent changes, and validate downstream dependencies.
Q: What is data observability and why does it matter? A: Data observability monitors data quality, freshness, volume, and lineage across the pipeline. It enables proactive issue detection, reduces debugging time, and builds trust in data products.
Q: How do you handle backfill scenarios? A: Use idempotent jobs, partition by date, monitor progress, validate outputs, and update downstream consumers. Consider using a dedicated backfill framework rather than ad-hoc scripts.
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
- Misidentifying the problem type â Always start by categorizing the problem
- Incorrect formula application â Verify the formula applies to your specific case
- Unit errors â Always check units are consistent throughout
- Sign errors â Pay careful attention to positive and negative values
- Rounding too early â Keep full precision until the final answer
- 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
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- 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
- Previous Topic â Build on the foundation laid here
- Next Topic â See how this concept extends to more advanced material
- Practice Problems â Additional exercises with solutions
- Video Explanation â Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids 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