Snowflake Scripting is the SQL-native procedural language built into Snowflake. If your logic is mostly SQL statements with some branching, looping, and error handling, it is usually simpler than Python or JavaScript procedures: no packages, no runtime, and it composes naturally with tasks. This tutorial walks through the building blocks and finishes with a pattern we reuse on client engagements.
1. Anatomy of a block
A Snowflake Scripting block has optional DECLARE, a required BEGIN ... END, and optional EXCEPTION.
EXECUTE IMMEDIATE $$
DECLARE
row_count INTEGER DEFAULT 0;
BEGIN
SELECT COUNT(*) INTO :row_count FROM my_db.public.orders;
RETURN 'orders: ' || row_count;
END;
$$;
Notes:
- Use a colon prefix (
:row_count) when a variable is referenced inside a SQL statement, and no colon in plain script expressions. - Anonymous blocks run through
EXECUTE IMMEDIATE(or theWITH ... CALLform); named logic belongs in a stored procedure.
2. A first stored procedure
CREATE OR REPLACE PROCEDURE purge_old_rows(tbl STRING, days INTEGER)
RETURNS STRING
LANGUAGE SQL
EXECUTE AS CALLER
AS
$$
DECLARE
deleted INTEGER;
BEGIN
DELETE FROM IDENTIFIER(:tbl)
WHERE loaded_at < DATEADD(day, -:days, CURRENT_TIMESTAMP());
deleted := SQLROWCOUNT;
RETURN 'Deleted ' || deleted || ' rows from ' || tbl;
END;
$$;
CALL purge_old_rows('my_db.staging.events', 30);
IDENTIFIER(:tbl) lets you parameterize object names safely without string-concatenated SQL. SQLROWCOUNT holds the rows affected by the last DML statement.
3. Branching and loops
DECLARE
i INTEGER DEFAULT 0;
BEGIN
IF (CURRENT_ROLE() = 'ACCOUNTADMIN') THEN
RETURN 'Please do not run this as ACCOUNTADMIN';
END IF;
WHILE (i < 3) DO
i := i + 1;
END WHILE;
FOR n IN 1 TO 5 DO
INSERT INTO audit.public.counter VALUES (:n);
END FOR;
RETURN 'done';
END;
Snowflake Scripting also supports CASE, REPEAT ... UNTIL, LOOP with BREAK/CONTINUE.
4. Cursors and RESULTSETs
Use a cursor to iterate over a query and act per row, for example granting access to every schema matching a pattern.
CREATE OR REPLACE PROCEDURE grant_read_on_schemas(db STRING, role_name STRING)
RETURNS STRING
LANGUAGE SQL
EXECUTE AS CALLER
AS
$$
DECLARE
c CURSOR FOR
SELECT schema_name FROM IDENTIFIER(:db || '.INFORMATION_SCHEMA.SCHEMATA')
WHERE schema_name <> 'INFORMATION_SCHEMA';
n INTEGER DEFAULT 0;
BEGIN
FOR rec IN c DO
EXECUTE IMMEDIATE 'GRANT USAGE ON SCHEMA ' || db || '.' || rec.schema_name || ' TO ROLE ' || role_name;
n := n + 1;
END FOR;
RETURN 'Granted on ' || n || ' schemas';
END;
$$;
A RESULTSET is the right tool when you want to return a table from a procedure:
CREATE OR REPLACE PROCEDURE top_customers(n INTEGER)
RETURNS TABLE (customer_id NUMBER, revenue NUMBER)
LANGUAGE SQL
AS
$$
DECLARE
res RESULTSET DEFAULT (
SELECT customer_id, SUM(amount) AS revenue
FROM sales.public.orders GROUP BY customer_id
ORDER BY revenue DESC LIMIT :n);
BEGIN
RETURN TABLE(res);
END;
$$;
CALL top_customers(10);
5. Exception handling
Declare custom exceptions, raise them, and catch built-in error variables.
DECLARE
bad_input EXCEPTION (-20001, 'Input table name is required');
BEGIN
-- ... work ...
RETURN 'ok';
EXCEPTION
WHEN bad_input THEN
RETURN SQLERRM;
WHEN STATEMENT_ERROR THEN
RETURN 'Statement failed: ' || SQLCODE || ' ' || SQLERRM || ' (state ' || SQLSTATE || ')';
WHEN OTHER THEN
RAISE;
END;
Custom exception numbers must fall in the range -20000 to -20999. Always end with WHEN OTHER THEN RAISE unless you truly intend to swallow errors; a silent failure inside a scheduled task is the hardest kind to debug.
6. Caller's rights vs owner's rights
EXECUTE AS OWNER(the default) runs with the owner's privileges. Good for controlled, narrow operations that users should run without direct table access. Owner's rights procedures cannot see the caller's session variables or run caller-context commands likeUSE.EXECUTE AS CALLERruns with the caller's privileges and session. Needed for utilities that operate on whatever the caller can see.
Prefer owner's rights with a dedicated, least-privilege role for pipelines, and caller's rights for admin helpers. Pair this with your RBAC model so procedures never run under an over-privileged role.
7. A reusable pattern: audited procedure wrapper
Create a log table once:
CREATE TABLE IF NOT EXISTS ops.public.proc_log (
run_id STRING DEFAULT UUID_STRING(),
proc_name STRING,
status STRING,
message STRING,
logged_at TIMESTAMP_LTZ DEFAULT CURRENT_TIMESTAMP()
);
Then structure each procedure to log success and failure:
CREATE OR REPLACE PROCEDURE load_daily_sales()
RETURNS STRING
LANGUAGE SQL
AS
$$
BEGIN
INSERT INTO sales.public.fact_sales
SELECT * FROM sales.staging.sales_raw
WHERE load_date = CURRENT_DATE();
INSERT INTO ops.public.proc_log (proc_name, status, message)
VALUES ('load_daily_sales', 'SUCCESS', 'rows=' || SQLROWCOUNT);
RETURN 'SUCCESS';
EXCEPTION
WHEN OTHER THEN
INSERT INTO ops.public.proc_log (proc_name, status, message)
VALUES ('load_daily_sales', 'FAILED', SQLERRM);
RAISE;
END;
$$;
Re-raising after logging means a calling task still shows as failed, so your alerts and retries keep working.
8. Scheduling it
CREATE OR REPLACE TASK load_daily_sales_task
WAREHOUSE = etl_wh
SCHEDULE = 'USING CRON 0 2 * * * UTC'
AS
CALL load_daily_sales();
ALTER TASK load_daily_sales_task RESUME;
For multi-step dependencies, use task graphs rather than chaining calls in one giant procedure.
Gotchas
- Variables used in SQL need the colon prefix; forgetting it causes confusing 'invalid identifier' errors.
- Keep procedures set-based. Row-by-row cursor loops with a DML per row are slow and costly; use them for orchestration, not bulk transformation.
- Dynamic SQL via
EXECUTE IMMEDIATEwith concatenated input is an injection risk. PreferIDENTIFIER()and bind variables withUSING. - Version procedures in Git and deploy them with your CI/CD pipeline rather than editing them in worksheets.
- Test with
CALLin a cloned dev database before promoting.
When to choose something else
Use Python (Snowpark) procedures for complex logic, libraries, or ML. Use dynamic tables for declarative incremental pipelines. Use Snowflake Scripting when the work is SQL orchestration, maintenance utilities, or controlled administrative operations.
Need senior Snowflake engineers to review your stored procedures, build out an orchestration layer, or take over a migration? Get in touch with PowderInsights and tell us about your project.