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

Snowflake Advanced Task Patterns

đŸŸĸ Free Lesson

Snowflake Advanced Task Patterns

Advanced task patterns in Snowflake enable complex workflow orchestration with dependencies, error handling, conditional logic, and dynamic SQL execution.

Advanced Task DAG: Error Handling FlowEntry TaskCRON ScheduleIF ConditionCheck DataTask AProcess DataTask BHandle ErrorTask CValidateD1: NotifyD2: LogTRUEFALSETRY/CATCH pattern with conditional branching and parallel notifications

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:

  1. Entry Task (CRON: 0 6 * * *) → IF condition
  2. Task A: Process Data (when condition = TRUE) or Task B: Handle Error (when condition = FALSE)
  3. Join → Task C: Validate
  4. 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

PatternImplementationUse Case
DAGMultiple AFTER dependenciesComplex ETL
Fan-outMultiple tasks after oneParallel processing
Fan-inMultiple tasks before oneAggregation
ConditionalIF/ELSE in stored procDecision trees
DynamicEXECUTE IMMEDIATESchema-aware

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