How to Create a Task in Snowflake: Syntax and Example
To create a task in Snowflake, use the
CREATE TASK statement with a name, schedule, and SQL statement to run. Tasks automate running SQL commands on a schedule or after other tasks complete.Syntax
The CREATE TASK statement defines a task with these parts:
- Task name: Unique identifier for the task.
- Warehouse: The compute resource to run the task.
- Schedule: When the task runs, using a cron expression or interval.
- SQL statement: The SQL command the task executes.
- After clause (optional): To chain tasks by running after another task.
sql
CREATE TASK task_name WAREHOUSE = warehouse_name SCHEDULE = 'USING CRON cron_expression' AS sql_statement;
Example
This example creates a task named daily_update that runs every day at 1 AM using the my_wh warehouse. It runs a simple SQL update statement.
sql
CREATE OR REPLACE TASK daily_update WAREHOUSE = my_wh SCHEDULE = 'USING CRON 0 1 * * * UTC' AS UPDATE sales SET status = 'processed' WHERE status = 'pending'; -- To start the task after creation ALTER TASK daily_update RESUME;
Output
Task daily_update created and scheduled to run daily at 1 AM UTC.
Common Pitfalls
- Forgetting to
RESUMEthe task after creation; tasks are created in a suspended state. - Not specifying a warehouse; the task needs a warehouse to run.
- Using incorrect cron syntax; Snowflake requires UTC time and specific cron format.
- Not granting necessary privileges to the user creating or running the task.
sql
/* Wrong: Task created but not resumed, so it won't run */ CREATE TASK my_task WAREHOUSE = my_wh SCHEDULE = 'USING CRON 0 0 * * * UTC' AS SELECT CURRENT_TIMESTAMP(); /* Right: Resume the task to activate it */ ALTER TASK my_task RESUME;
Quick Reference
| Clause | Description |
|---|---|
| CREATE TASK task_name | Defines the task with a unique name |
| WAREHOUSE = warehouse_name | Specifies the warehouse to run the task |
| SCHEDULE = 'USING CRON cron_expression' | Sets the schedule in cron format (UTC) |
| AS sql_statement | The SQL command the task executes |
| ALTER TASK task_name RESUME | Starts the task after creation |
| AFTER other_task | Runs this task after another task completes |
Key Takeaways
Use CREATE TASK with warehouse, schedule, and SQL to automate commands in Snowflake.
Always RESUME the task after creation to activate it.
Schedules use UTC time and cron syntax for timing.
Tasks need proper privileges and a warehouse to run.
You can chain tasks using the AFTER clause for sequential execution.
