Snowflake Advanced Task Patterns
Advanced task patterns in Snowflake enable complex workflow orchestration with dependencies, error handling, conditional logic, and dynamic SQL execution.
What are Advanced Tasks?
- Build complex DAGs with AFTER dependencies
- Use TRY/CATCH for resilient error handling
- Execute dynamic SQL with EXECUTE IMMEDIATE
Architecture Overview
The advanced task workflow architecture follows this flow:
- Entry Task (CRON: 0 6 * * *) â IF condition
- Task A: Process Data (when condition = TRUE) or Task B: Handle Error (when condition = FALSE)
- Join â Task C: Validate
- Fork â Task D1: Notify and Task D2: Notify
Task History & Monitoring
- Execution history and error tracking
- Performance metrics (duration, credits)
- Dependency visualization (DAG)
Scheduling Patterns
- CRON expressions
- Event-driven triggers
- Dependency chains
Error Handling
- TRY/CATCH blocks
- Automatic retries
- Alert on failure
Dynamic Operations
- Dynamic SQL execution
- Parameterized queries
- Conditional logic
Task Dependencies
DAG Workflow
-- Create task DAG
CREATE OR REPLACE TASK task_1 WAREHOUSE = wh AS INSERT INTO t1 SELECT 1;
CREATE OR REPLACE TASK task_2 WAREHOUSE = wh AFTER task_1 AS INSERT INTO t2 SELECT 2;
CREATE OR REPLACE TASK task_3 WAREHOUSE = wh AFTER task_1 AS INSERT INTO t3 SELECT 3;
CREATE OR REPLACE TASK task_4 WAREHOUSE = wh AFTER task_2 AND task_3 AS INSERT INTO t4 SELECT 4;
-- Resume all tasks
ALTER TASK task_1 RESUME;
ALTER TASK task_2 RESUME;
ALTER TASK task_3 RESUME;
ALTER TASK task_4 RESUME;
Conditional Branching
CREATE OR REPLACE TASK conditional_task
WAREHOUSE = compute_wh
SCHEDULE = '1 HOUR'
AS
BEGIN
-- Check condition
LET record_count := (SELECT COUNT(*) FROM staging_table);
IF (:record_count > 0) THEN
-- Process data
INSERT INTO target_table
SELECT * FROM staging_table;
-- Send success notification
CALL SYSTEM$SEND_EMAIL(
'my_integration',
'admin@company.com',
'Data Loaded',
'Successfully loaded ' || :record_count || ' records'
);
ELSE
-- Log no data
INSERT INTO task_log (task_name, status, message, timestamp)
VALUES ('conditional_task', 'SKIPPED', 'No records to process', CURRENT_TIMESTAMP());
END IF;
END;
Dynamic SQL Tasks
CREATE OR REPLACE TASK dynamic_etl_task
WAREHOUSE = compute_wh
SCHEDULE = 'USING CRON 0 2 * * * America/New_York'
AS
BEGIN
-- Get list of tables to process
LET tables := (SELECT ARRAY_AGG(table_name) FROM metadata_table WHERE active = TRUE);
FOR i IN 0 TO ARRAY_SIZE(:tables) - 1 DO
LET table_name := :tables[i];
-- Dynamic SQL
LET sql := 'INSERT INTO target.' || :table_name ||
' SELECT * FROM source.' || :table_name ||
' WHERE processed = FALSE';
EXECUTE IMMEDIATE :sql;
-- Log execution
INSERT INTO task_log (task_name, table_name, status, timestamp)
VALUES ('dynamic_etl', :table_name, 'SUCCESS', CURRENT_TIMESTAMP());
END FOR;
END;
Error Handling Patterns
CREATE OR REPLACE TASK resilient_task
WAREHOUSE = compute_wh
SCHEDULE = '5 MINUTE'
AS
BEGIN
-- Try block
BEGIN
INSERT INTO target_table
SELECT * FROM source_table WHERE processed = FALSE;
-- Update source as processed
UPDATE source_table SET processed = TRUE WHERE processed = FALSE;
EXCEPTION
WHEN OTHER THEN
-- Log error
INSERT INTO error_log (task_name, error_code, error_message, timestamp)
VALUES ('resilient_task', SQLCODE, SQLERRM, CURRENT_TIMESTAMP());
-- Send alert
CALL SYSTEM$SEND_EMAIL(
'alert_integration',
'ops@company.com',
'Task Failed: resilient_task',
'Error: ' || SQLERRM
);
END;
END;
Task Monitoring
-- Task execution history
SELECT
name,
state,
completed_time,
scheduled_time,
error_code,
error_message,
DATEDIFF(second, scheduled_time, completed_time) as duration_seconds
FROM TABLE(INFORMATION_SCHEMA.TASK_HISTORY(
START_TIME => DATEADD(day, -7, CURRENT_TIMESTAMP()),
TASK_NAME => 'resilient_task'
))
ORDER BY scheduled_time DESC;
-- Task dependency analysis
SELECT
t.name as task_name,
t.state,
t.schedule,
t.allow_overlapping_execution,
t.error_integration
FROM TABLE(INFORMATION_SCHEMA.TASKS()) t
ORDER BY t.name;
Advanced Patterns
| Pattern | Implementation | Use Case |
|---|---|---|
| DAG | Multiple AFTER dependencies | Complex ETL |
| Fan-out | Multiple tasks after one | Parallel processing |
| Fan-in | Multiple tasks before one | Aggregation |
| Conditional | IF/ELSE in stored proc | Decision trees |
| Dynamic | EXECUTE IMMEDIATE | Schema-aware |
See Also
- Streams & Tasks â Track DML changes with streams for CDC patterns
- ETL Pipelines â Design end-to-end data transformation workflows
- Stored Procedures â Implement complex business logic in SQL and JavaScript
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