CertSafari
    Snowflake SnowPro Advanced: Data Engineer (DEA-C02)· Lessons

    Domain 5 · Lesson 18/22

    Snowflake stored procedures: Scripting, JavaScript, Snowpark, transactions and rights

    Design, build, and leverage stored procedures.

    21 min read
    3.57% of exam
    12 sources
    Published 20 Oct 2026
    Docs as of 18 Oct 2026

    What you will be able to do

    • Write a stored procedure in Snowflake Scripting using DECLARE, BEGIN … END, cursors and an EXCEPTION handler, and run one as an anonymous procedure with WITH … CALL
    • Write a JavaScript stored procedure with the snowflake object and avoid the argument-case trap
    • Write a Snowpark Python stored procedure whose handler receives the Session from Snowflake
    • Predict how explicit, implicit and DDL-triggered commits behave inside a procedure, and use COMMIT or ROLLBACK in an error handler
    • Choose between EXECUTE AS OWNER, CALLER and RESTRICTED CALLER based on the privileges and session state the procedure needs

    Key concept

    The procedure boundary — A stored procedure call is a boundary. A transaction can't start on one side of it and finish on the other, and the EXECUTE AS setting decides whose privileges and whose session state the code inside can use.

    1.What a stored procedure adds to SQL

    A stored procedure adds procedural code to Snowflake. You get branching, loops and multi-statement logic, all run by one CALL. A common example is a cleanup job that deletes rows older than a cut-off date from several tables. If you put every DELETE in one procedure and pass the date as a parameter, users call one command instead of remembering each table. When the database grows, you update the procedure, and every caller gets the new behaviour.

    The logic itself is the handler, and you can write it in Snowflake Scripting (SQL), JavaScript, Python, Java or Scala. You create the procedure with CREATE PROCEDURE and run it with CALL. The handler language also decides where the code can live. Snowflake Scripting and JavaScript handlers must be in-line, inside the CREATE PROCEDURE statement. Python, Java and Scala handlers can also be loaded from a stage.

    Where each handler language's code can live
    Handler languageHandler location
    Snowflake ScriptingIn-line
    JavaScriptIn-line
    PythonIn-line or staged
    JavaIn-line or staged
    ScalaIn-line or staged

    Not every procedure has to be a permanent schema object. A TEMPORARY procedure lasts only for the current session. An anonymous procedure is created and called in one statement, then dropped. Neither one needs the CREATE PROCEDURE privilege on the schema. That makes them handy for one-off work by roles that can't publish procedures.

    Checkpoint 1 of 9· Check yourself

    An analyst's role has no CREATE PROCEDURE privilege on any schema. They need to run some multi-statement cleanup logic once, and they can't be granted new privileges. Which approach works?

    Sources1

    2.Snowflake Scripting procedures: blocks, cursors and exceptions

    A Snowflake Scripting procedure is declared with LANGUAGE SQL, and its body is a block. The optional DECLARE section names variables, cursors, RESULTSETs, nested procedures and exceptions. BEGIN … END holds the statements, and an optional EXCEPTION section handles errors. In Snowsight or SnowSQL, the body must be wrapped in string delimiters (' or $$). The recommended limit for a Snowflake Scripting body is 100 KB of source code.

    Arguments are referenced by name in expressions. Inside a SQL statement, an argument needs a colon prefix, as in WHERE id = :id. Snowflake Scripting is the only handler language with output arguments. An argument marked OUT (or OUTPUT) can be changed in the body, and its final value goes back to the caller, such as another procedure or an anonymous block. An IN argument (the default) can also be changed, but its new value stays inside the procedure. A procedure can't be overloaded by changing only IN to OUT: the second CREATE PROCEDURE fails with an error saying the procedure already exists.

    A cursor walks through a query result one row at a time, in four steps. You declare it with its query, OPEN it (this is when the query actually runs), FETCH rows into variables, and CLOSE it. ? placeholders in the cursor query are bound in the OPEN … USING clause. If you FETCH past the last row, the variables get NULLs. Without an outer ORDER BY, the row order has no guarantee.

    A cursor with bind parameters, opened with USING and read with FETCHsql
    DECLARE
      id INTEGER DEFAULT 0;
      minimum_price NUMBER(13,2) DEFAULT 22.00;
      maximum_price NUMBER(13,2) DEFAULT 33.00;
      c1 CURSOR FOR SELECT id FROM invoices WHERE price > ? AND price < ?;
    BEGIN
      OPEN c1 USING (minimum_price, maximum_price);
      FETCH c1 INTO id;
      RETURN id;
    END;

    Each block can have at most one exception handler, but that handler can contain several WHEN clauses. WHEN OTHER THEN catches any exception not already named. The handler covers only the statements between BEGIN and EXCEPTION, not the DECLARE section. Each handler statement can be any SQL statement, including CALL, so a handler can run ROLLBACK or COMMIT. You can declare your own exceptions with a number between -20000 and -20999. Each WHEN clause is either an EXIT or a CONTINUE handler. An EXIT handler, the default, runs its statements and then leaves the current block, so any statements after the failing one are skipped. In an inner block with no RETURN in the handler, execution carries on in the outer block. A CONTINUE handler runs its statements and then resumes at the statement right after the one that raised the error, and a single EXCEPTION section can mix both kinds. If the procedure returns a value, every exit path must return one, including each EXIT-type WHEN clause.

    An anonymous procedure uses WITH … AS PROCEDURE … CALL. The definition and the call are one statement, and the body must be wrapped in delimiters.

    Creating and calling an anonymous Snowflake Scripting procedure in one statementsql
    WITH anonymous_output_message AS PROCEDURE (message VARCHAR)
      RETURNS VARCHAR NOT NULL
      LANGUAGE SQL
      AS
      $$
      BEGIN
        RETURN message;
      END;
      $$
    CALL anonymous_output_message('Hello World');

    Checkpoint 2 of 9· Fill the gap

    This anonymous procedure has a Snowflake Scripting handler. Which keyword completes its LANGUAGE clause?

    WITH anonymous_output_message AS PROCEDURE (message VARCHAR)
      RETURNS VARCHAR NOT NULL
      LANGUAGE  ? 
      AS
      $$
      BEGIN
        RETURN message;
      END;
      $$
    CALL anonymous_output_message('Hello World');

    Sources2345

    3.JavaScript procedures and the snowflake object

    A JavaScript procedure runs SQL through an object called snowflake, which exists without being declared. snowflake.createStatement({sqlText: ...}) returns a Statement. Calling execute() on it returns a ResultSet, and you step through rows with next() and read them with getColumnValue(). snowflake.execute() does the same in one call. Timestamps come back as SfDate, an extension of the JavaScript Date.

    The JavaScript engine is deliberately restricted. It has no eval(), no way to import third-party libraries, and no network or disk access. JavaScript numbers also keep full precision only up to about ±2^53. A large NUMBER read with getColumnValue() can lose digits. Reading it with getColumnValueAsString() and casting it back in SQL avoids this.

    The trap that fails silently is argument case. In the SQL part of the definition, Snowflake uppercases unquoted identifiers. The JavaScript part keeps the case you write. So an argument declared as argument1 must be referenced as ARGUMENT1 in the JavaScript code.

    The argument is declared in lower case but must be read in upper casesql
    CREATE PROCEDURE f(argument1 VARCHAR)
    RETURNS VARCHAR
    LANGUAGE JAVASCRIPT
    AS
    $$
    var local_variable1 = argument1;  // Incorrect
    var local_variable2 = ARGUMENT1;  // Correct
    $$;

    Errors are handled with normal JavaScript try/catch. The caught error object has code, state, message and stackTraceTxt. You can also throw your own exception, for example to reject a negative input. When the statements are wrapped in a transaction, the catch block can roll all of them back. The transactions section below uses this pattern.

    Checkpoint 3 of 9· Check yourself

    A developer creates CREATE PROCEDURE purge(cutoff_date VARCHAR) ... LANGUAGE JAVASCRIPT and builds a DELETE statement in the JavaScript body from cutoff_date. The procedure doesn't do what it should, and no clear error points at the argument. Which change fixes it?

    Sources6

    4.Snowpark procedures: the Session arrives as an argument

    A Snowpark procedure is written in Python, Java or Scala and works on data through the Snowpark API. How you build a Session and DataFrames in client code is covered in Snowpark Session and DataFrame construction. Inside a procedure, you don't build the Session at all. You make it the handler's first parameter, and when the procedure is called, Snowflake creates a Session and passes it in.

    A Python procedure whose run handler takes session as its first parametersql
    CREATE OR REPLACE PROCEDURE myproc(from_table STRING, to_table STRING, count INT)
      RETURNS STRING
      LANGUAGE PYTHON
      RUNTIME_VERSION = '3.12'
      PACKAGES = ('snowflake-snowpark-python')
      HANDLER = 'run'
    as
    $$
    def run(session, from_table, to_table, count):
      session.table(from_table).limit(count).write.save_as_table(to_table)
      return "SUCCESS"
    $$;

    Notice the mismatch between the signatures. The handler takes four parameters, but CREATE PROCEDURE declares three, and CALL myproc('table_a', 'table_b', 5) passes three. The Session is implicit: you never declare it in the SQL signature and never pass it in a call. The snowflake-snowpark-python package must be listed in PACKAGES.

    The Session you receive is not neutral. Its privileges, current database and current schema depend on whether the procedure runs with caller's or owner's rights. A Snowpark handler that works when its author tests it can fail for another role for exactly this reason. Errors are caught with normal Python or Java exception handling. An uncaught exception becomes a Snowflake error that includes the stack trace. One more rule: a child query started asynchronously and still running when the procedure ends is cancelled. Fire-and-forget isn't supported.

    Checkpoint 4 of 9· Fill the gap

    The handler's first parameter is a Session that Snowflake creates and passes in, and the call never supplies it. Which package must this procedure list so that the handler can use that Session?

    CREATE OR REPLACE PROCEDURE myproc(from_table STRING, to_table STRING, count INT)
      RETURNS STRING
      LANGUAGE PYTHON
      RUNTIME_VERSION = '3.12'
      PACKAGES = (' ? ')
      HANDLER = 'run'
    as
    $$
    def run(session, from_table, to_table, count):
      session.table(from_table).limit(count).write.save_as_table(to_table)
      return "SUCCESS"
    $$;

    Sources789

    5.Transactions inside a procedure

    A transaction is a set of statements that is committed or rolled back as one unit. You can start one explicitly with BEGIN TRANSACTION (or BEGIN WORK) and end it with COMMIT or ROLLBACK. Transactions also start and end implicitly. With AUTOCOMMIT at its default of TRUE, every statement outside an explicit transaction is its own single-statement transaction. It commits if it succeeds and rolls back if it fails.

    DDL commits the transaction. Each DDL statement, including CTAS, runs as its own transaction. If a transaction is open, the DDL statement commits it first. So you can't roll back DDL, and any DML that ran before it in the same transaction is committed too. Keep explicit transactions to DML and queries only.

    The procedure boundary adds three rules. First, a transaction can live inside a procedure, or a whole procedure call can sit inside a transaction, but a transaction can't cross the boundary. If you begin a transaction before the CALL and try to commit it inside the procedure, you get *Modifying a transaction that has started at a different scope is not allowed.* Second, if a transaction is still open when the procedure ends, Snowflake rolls it back and raises an error. That's true whether the transaction started explicitly or implicitly. Third, nested procedures follow the same rule: if procedure A calls procedure B, each BEGIN TRANSACTION in A needs its COMMIT or ROLLBACK in A, and the same goes for B. Also, never change AUTOCOMMIT inside a procedure, because it raises an error.

    Error handling decides what survives. When a statement fails inside a transaction, only that statement's changes are rolled back, and the transaction stays open. Take a Snowflake Scripting procedure that inserts 1, then fails on a bad insert, then would insert 2 and commit. If the exception isn't handled, the procedure never finishes, COMMIT never runs, and the open transaction is rolled back, so neither row is kept. If an EXCEPTION handler catches the error and commits, the row with 1 is kept. JavaScript uses the same pattern with try/catch:

    JavaScript: commit at the end of try, roll back in catchjavascript
      var result = "";
      snowflake.execute( {sqlText: "BEGIN WORK;"} );
      try {
          snowflake.execute( {sqlText: "DELETE FROM child;"} );
          snowflake.execute( {sqlText: "DELETE FROM parent;"} );
          if (FORCE_FAILURE === "fail")  {
              // To see what happens if there is a failure/rollback,
              snowflake.execute( {sqlText: "DELETE FROM no_such_table;"} );
              }
          snowflake.execute( {sqlText: "COMMIT WORK;"} );
          result = "Succeeded";
          }
      catch (err)  {
          snowflake.execute( {sqlText: "ROLLBACK WORK;"} );
          return "Failed: " + err;   // Return a success/error indicator.
          }
      return result;

    Checkpoint 5 of 9· Fill the gap

    If DELETE FROM no_such_table fails, the DELETEs on child and parent must leave no trace. Which keyword belongs in the statement inside the catch block?

      var result = "";
      snowflake.execute( {sqlText: "BEGIN WORK;"} );
      try {
          snowflake.execute( {sqlText: "DELETE FROM child;"} );
          snowflake.execute( {sqlText: "DELETE FROM parent;"} );
          if (FORCE_FAILURE === "fail")  {
              // To see what happens if there is a failure/rollback,
              snowflake.execute( {sqlText: "DELETE FROM no_such_table;"} );
              }
          snowflake.execute( {sqlText: "COMMIT WORK;"} );
          result = "Succeeded";
          }
      catch (err)  {
          snowflake.execute( {sqlText: " ?  WORK;"} );
          return "Failed: " + err;   // Return a success/error indicator.
          }
      return result;

    Sources10

    6.Owner's rights vs caller's rights

    Every procedure runs with either the owner's rights or the caller's rights, never both at once. The creator chooses with EXECUTE AS. If you leave it out, the procedure runs with owner's rights. Snowflake picks this default because owner's rights give the procedure less access to the caller's environment. The owner can switch modes later with ALTER PROCEDURE.

    An owner's rights procedure (EXECUTE AS OWNER) runs mostly with the privileges of the role that owns it. This is how you delegate a task. Say a role has no DELETE on a staging table but needs to purge rows older than 90 days. You give it USAGE on an owner's rights procedure that does that one delete, and the role never gets general table privileges. The cost is isolation from the caller's session. The procedure uses the warehouse the caller is using, but it resolves names in the database and schema where it was created. It can't view, set or unset the caller's session variables. It also sees only a fixed list of the caller's session parameters, such as DATE_OUTPUT_FORMAT, TIMEZONE and QUERY_TAG.

    A caller's rights procedure (EXECUTE AS CALLER) runs with the privileges of the role that calls it, and it can see that caller's session. It can read session variables set with SET before the call and use them in queries. It can also set variables that remain after it returns, though Snowflake advises against leaving them set. It grants the caller nothing new. If the caller can't delete from a table, a caller's rights procedure can't either.

    A caller's rights Scripting procedure reading a session variablesql
    CREATE OR REPLACE PROCEDURE use_sql_variable_proc()
    RETURNS NUMBER
    LANGUAGE SQL
    EXECUTE AS CALLER
    AS
    DECLARE
      sess_var_x_2 NUMBER;
    BEGIN
      sess_var_x_2 := 2 * $example_use_variable;
      RETURN sess_var_x_2;
    END;

    EXECUTE AS RESTRICTED CALLER is a third option. The procedure runs with caller's rights, but only with a subset of them: an administrator uses caller grants to control which of the caller's rights the procedure may run with. Choose it over plain CALLER when the procedure needs to run in the caller's context but shouldn't be able to use everything the caller can do.

    Choosing an EXECUTE AS mode
    ModePrivileges usedCaller's session variablesUse it when
    EXECUTE AS OWNER (default)Mostly the owning role'sCannot view, set or unsetDelegating one narrow task, such as a purge, to a role without broader grants
    EXECUTE AS CALLERThe calling role'sCan read and setThe logic depends on the caller's session state or must stay within the caller's privileges
    EXECUTE AS RESTRICTED CALLERThe caller's, limited by caller grants an administrator setsRuns as a caller's rights procedureYou want caller's rights, but only a subset of the caller's privileges

    Checkpoint 6 of 9· Check yourself

    Your ops team wants a support role to purge rows older than 90 days from a staging table. The support role has no DELETE privilege on that table and must not get general table privileges. Which setup does the job?

    Checkpoint 7 of 9· Exam question

    By default, when a stored procedure is created in Snowflake without specifying an EXECUTE AS clause, which privilege model does it run under?

    Checkpoint 8 of 9· Exam question

    A data engineering team builds a stored procedure that must read a session variable the calling application sets with SET before invoking it, then use that value inside a dynamic query. Which design lets the procedure read that caller-set session variable?

    Checkpoint 9 of 9· Exam question

    A platform team wants a role with no direct DELETE privilege on a staging table to be able to run a cleanup routine that purges rows older than 90 days, without granting that role broader table privileges. Which stored procedure design achieves this safely?

    Sources1112

    Sources

    (12)

    Every claim above is drawn from one of these pages, quoted as it was written on the date shown.

    1. 1.
      “Once you have a handler, you can create a procedure with a CREATE PROCEDURE command, then call the procedure with a CALL statement.”
      ↩︎ What a stored procedure adds to SQL
      “creating a procedure in one of the following ways doesn’t require the CREATE PROCEDURE privilege”
      ↩︎ What a stored procedure adds to SQL
      “This allows the stored procedure owner to delegate the power to perform specified operations to users who otherwise could not do so.”
      ↩︎ Checkpoint
    2. 2.
      “In the body of the stored procedure (the AS clause), you use a Snowflake Scripting block.”
      ↩︎ Snowflake Scripting procedures: blocks, cursors and exceptions
      “Stored procedures written in languages other than SQL don’t support output arguments.”
      ↩︎ Snowflake Scripting procedures: blocks, cursors and exceptions
    3. 3.
      “the query is not executed until you open the cursor by executing the OPEN command”
      ↩︎ Snowflake Scripting procedures: blocks, cursors and exceptions
    4. 4.
      “Snowflake supports no more than one exception handler per block.”
      ↩︎ Snowflake Scripting procedures: blocks, cursors and exceptions
      “The block executes the statements in the handler and continues with the statement immediately following the one that caused the error.”
      ↩︎ Snowflake Scripting procedures: blocks, cursors and exceptions
    5. 6.
      “This code uses an object named snowflake, which is a special object that exists without being declared.”
      ↩︎ JavaScript procedures and the snowflake object
      “The JavaScript code cannot call the JavaScript eval() function.”
      ↩︎ JavaScript procedures and the snowflake object
      “If an error occurs, then your catch block can roll back all of the statements (if you put the statements in a transaction).”
      ↩︎ JavaScript procedures and the snowflake object
      “Argument names are case-insensitive in the SQL portion of the stored procedure code, but are case-sensitive in the JavaScript portion.”
      ↩︎ Exam trap 3
      “Creating and calling an anonymous procedure does not require a role with CREATE PROCEDURE schema privileges.”
      ↩︎ Checkpoint
      “Argument names are case-insensitive in the SQL portion of the stored procedure code, but are case-sensitive in the JavaScript portion.”
      ↩︎ Checkpoint
      “Both fail when using an owner’s rights stored procedure even if the caller is the owner.”
      ↩︎ Prediction
    6. 7.
      “Specify the Snowpark Session object as the first argument of your method or function.”
      ↩︎ Snowpark procedures: the Session arrives as an argument
    7. 8.
      “In the CREATE PROCEDURE statement for a procedure written in Java, Python, or Scala, do not define the argument for the Snowpark Session object.”
      ↩︎ Snowpark procedures: the Session arrives as an argument
    8. 9.
      “is determined by whether the stored procedure runs with caller’s rights or owner’s rights”
      ↩︎ Snowpark procedures: the Session arrives as an argument
    9. 10.
      “Each DDL statement executes as a separate transaction.”
      ↩︎ Transactions inside a procedure
      “Modifying a transaction that has started at a different scope is not allowed.”
      ↩︎ Transactions inside a procedure
      “Do not change AUTOCOMMIT settings inside a stored procedure.”
      ↩︎ Transactions inside a procedure
      “the stored procedure never completes, and the COMMIT is never executed, so the open transaction is implicitly rolled back”
      ↩︎ Transactions inside a procedure
      “a transaction cannot be partly inside and partly outside a stored procedure”
      ↩︎ Key concept
      “Because a DDL statement is its own transaction, you cannot roll back a DDL statement”
      ↩︎ Exam trap 1
      “Regardless of whether the stored procedure’s active transaction was started explicitly or implicitly, Snowflake rolls back the active transaction and issues an error message.”
      ↩︎ Exam trap 2
      “Implicitly commits the active transaction.”
      ↩︎ Prediction
    10. 11.
      “The default is owner’s rights.”
      ↩︎ Owner's rights vs caller's rights
      “the owner can delegate specific administrative tasks, such as cleaning up old data, to another role”
      ↩︎ Owner's rights vs caller's rights
      “Cannot view, set, or unset the caller’s session variables.”
      ↩︎ Owner's rights vs caller's rights
      “Inherit the current warehouse of the caller.”
      ↩︎ Owner's rights vs caller's rights
      “a caller’s rights stored procedure can read the caller’s session variables and use them in a query.”
      ↩︎ Owner's rights vs caller's rights
      “An administrator can use caller grants to control which of the caller’s rights the stored procedure can run with.”
      ↩︎ Owner's rights vs caller's rights
      “The default is owner’s rights.”
      ↩︎ Exam trap 4
      “Use the database and schema that the stored procedure is created in, not the database and schema that the caller is currently using.”
      ↩︎ Exam trap 5
    11. 12.
      “will execute as a caller’s rights procedure, but might not be able to run with all of the caller’s privileges”
      ↩︎ Owner's rights vs caller's rights

    Ready to test yourself?

    Practise the 13 questions on this subdomain.

    Spotted a mistake, or was something unclear? Tell us.