Snowflake SQL Tutorial 151 - A Procedure That Vanishes After One Statement, And The Row It Left Behind

Snowflake SQL · Episode 151

In this post we are going to cover anonymous procedures in Snowflake.

An anonymous procedure is a procedure you never create. You declare it inside a WITH clause, you call it in the same statement, and when that statement is over it is gone. There is nothing in the catalog and nothing to drop.

It exists for exactly one statement. But what it does while it is alive is permanent, and that pairing is the whole post.

We will start with the smallest one there is and build it up step by step. Every query below was run on a real Snowflake account, and every result and every error you see is what it gave back.

Episode 151 of the Snowflake SQL: Zero to Hero series on TechBrothersIT.

Let's create some sample data

First let's see where the session is pointing.

Query
SELECT CURRENT_DATABASE()  AS THE_DATABASE,
       CURRENT_SCHEMA()    AS THE_SCHEMA,
       CURRENT_VERSION()   AS THE_VERSION;
Result1 row · 3 columns
THE_DATABASETHE_SCHEMATHE_VERSION
DEMO_DBPUBLIC10.35.101

Now a small sales table, and five rows in it.

Sample data
CREATE OR REPLACE TABLE SALES_T151 (
    SALE_ID INT,
    REGION  VARCHAR(10),
    AMOUNT  NUMBER(10,2)
);
Result1 row · 1 column
status
Table SALES_T151 successfully created.
Sample data
INSERT INTO SALES_T151 (SALE_ID, REGION, AMOUNT)
VALUES (1, 'north', 100.00), (2, 'south', 250.50),
       (3, 'east',   75.25), (4, 'west',  310.00),
       (5, 'north',  45.00);
Result1 row · 1 column
number of rows inserted
5

And a count to confirm what is in there.

Query
SELECT COUNT(*) AS HOW_MANY, SUM(AMOUNT) AS TOTAL_AMOUNT FROM SALES_T151;
Result1 row · 2 columns
HOW_MANYTOTAL_AMOUNT
5780.75

Five rows and a total of 780.75. That is everything this post reads.

Let's start with the smallest anonymous procedure

Here is the whole thing. Read the first line, and notice what is not there.

Query
WITH DOUBLE_T151 AS PROCEDURE (N NUMBER)
RETURNS NUMBER
LANGUAGE SQL
AS
BEGIN
    RETURN :N * 2;
END
CALL DOUBLE_T151(21);
Result1 row · 1 column
DOUBLE_T151
42

Forty two, so it ran and it worked.

Now look at the shape of what we wrote. There is no CREATE anywhere in it. The word PROCEDURE comes after AS, inside a WITH clause, and the name in front of it is just a label.

And the CALL at the bottom is part of the same statement. That is why it can see a name that nothing else can.

  • WITH, then the name you want to use
  • AS PROCEDURE, with the arguments after it
  • RETURNS, then LANGUAGE, then AS
  • the body
  • and then the statement that uses it, with no semicolon between them

Now let's wrap the body in dollar signs

Every procedure in this course so far has had its body between a pair of $$. Let's write the same one that way.

Query
WITH DOLLARS_T151 AS PROCEDURE (N NUMBER)
RETURNS NUMBER
LANGUAGE SQL
AS
$$
BEGIN
    RETURN :N * 2;
END;
$$
CALL DOLLARS_T151(21);
Result1 row · 1 column
DOLLARS_T151
42

Also forty two. Both spellings are fine, so use whichever you find easier to read.

Two things that are not optional

First let's leave out the RETURNS clause.

Query
WITH NORETURNS_T151 AS PROCEDURE ()
LANGUAGE SQL
AS
BEGIN
    RETURN 1;
END
CALL NORETURNS_T151();
Query failed — Snowflake returned an error
092226 (42601): SQL compilation error: stored procedure definition is missing return type

092226, missing return type. So RETURNS is required even though nothing is being registered anywhere.

And second, a body that is not a block. Just a RETURN, with no BEGIN and no END.

Query
WITH NOBLOCK_T151 AS PROCEDURE ()
RETURNS NUMBER
LANGUAGE SQL
AS
    RETURN 1;
CALL NOBLOCK_T151();
Query failed — Snowflake returned an error
001003 (42000): SQL compilation error:
syntax error line 5 at position 4 unexpected 'RETURN'.

001003. The body has to be a block, the same as it does in a procedure you create.

So where is the procedure now?

A moment ago that call gave us a number back. Let's ask the catalog about the name.

Query
SHOW PROCEDURES LIKE 'DOUBLE\\_T151';
Result0 rows · 16 columns · scroll →
created_onnameschema_nameis_builtinis_aggregateis_ansimin_num_argumentsmax_num_argumentsargumentsdescriptioncatalog_nameis_table_functionvalid_for_clusteringis_securesecretsexternal_access_integrations

Nothing at all. The grid is empty, so the name was never registered anywhere.

Let's ask a second way. Just call it again, on its own, as the next statement.

Query
CALL DOUBLE_T151(21);
Query failed — Snowflake returned an error
002139 (02000): SQL compilation error:
Unknown function DOUBLE_T151.

002139, unknown function. So the procedure existed for exactly one statement, and that statement is over.

And a third way, from the other end. Let's try to drop it.

Query
DROP PROCEDURE IF EXISTS DEMO_DB.PUBLIC.DOUBLE_T151(NUMBER);
Result1 row · 1 column
status
Drop statement executed successfully (DOUBLE_T151 already dropped).

Already dropped. There was never anything there to drop.

Two more ways to write that wrong

Let's declare one name and then call a different one.

Query
WITH MISMATCH_T151 AS PROCEDURE ()
RETURNS NUMBER
LANGUAGE SQL
AS
BEGIN
    RETURN 1;
END
CALL NOT_THAT_NAME_T151();
Query failed — Snowflake returned an error
002139 (02000): SQL compilation error:
Unknown function NOT_THAT_NAME_T151.

Unknown function again. The call has to name the procedure we just declared, because that label is the only thing that knows it exists.

And now a WITH clause with nothing after it at all.

Query
WITH LONELY_T151 AS PROCEDURE ()
RETURNS NUMBER
LANGUAGE SQL
AS
BEGIN
    RETURN 1;
END
Query failed — Snowflake returned an error
001003 (42000): SQL compilation error:
syntax error line 13 at position 40 unexpected '<EOF>'.

Unexpected end of file. The statement is not finished, because a declaration on its own is not a statement.

About that line number

The position in that message points further down than the statement above it. In the demo file this is the last statement, and an anonymous procedure has no terminator, so the comment block that follows it got read as part of the same statement. The code block above shows the statement without that comment. Nothing else about it was changed.

So what can go in the body?

Everything that can go in a procedure you create. Let's start with a DECLARE section and a SELECT ... INTO.

Query
WITH DECLARED_T151 AS PROCEDURE ()
RETURNS VARCHAR
LANGUAGE SQL
AS
DECLARE
    THE_LABEL VARCHAR DEFAULT 'it declared';
    HOW_MANY  NUMBER;
BEGIN
    SELECT COUNT(*) INTO :HOW_MANY FROM SALES_T151;
    RETURN :THE_LABEL || ' and counted ' || :HOW_MANY;
END
CALL DECLARED_T151();
Result1 row · 1 column
DECLARED_T151
it declared and counted 5

So the declare section works, and the body can read a table.

Now a loop.

Query
WITH LOOPED_T151 AS PROCEDURE ()
RETURNS VARCHAR
LANGUAGE SQL
AS
DECLARE
    OUT_TEXT VARCHAR DEFAULT '';
BEGIN
    FOR I IN 1 TO 3 DO
        OUT_TEXT := :OUT_TEXT || :I || ' ';
    END FOR;
    RETURN 'visited: ' || :OUT_TEXT;
END
CALL LOOPED_T151();
Result1 row · 1 column
LOOPED_T151
visited: 1 2 3

A FOR loop, behaving exactly the way it does anywhere else, inside something with no name.

And now an exception handler.

Query
WITH HANDLED_T151 AS PROCEDURE ()
RETURNS VARCHAR
LANGUAGE SQL
AS
BEGIN
    RAISE STATEMENT_ERROR;
    RETURN 'never reached';
EXCEPTION
    WHEN STATEMENT_ERROR THEN
        RETURN 'the handler ran in an anonymous procedure';
END
CALL HANDLED_T151();
Result1 row · 1 column
HANDLED_T151
the handler ran in an anonymous procedure

The handler ran. So everything from the last post applies here unchanged.

Now let's return rows instead of a value

Let's declare a RESULTSET, give it a query, and hand the rows back with RETURN TABLE.

Query
WITH TABLED_T151 AS PROCEDURE (CUTOFF NUMBER)
RETURNS TABLE (SALE_ID INT, THE_AMOUNT NUMBER(10,2))
LANGUAGE SQL
AS
DECLARE
    RS RESULTSET;
BEGIN
    RS := (SELECT SALE_ID, AMOUNT FROM SALES_T151 WHERE AMOUNT > :CUTOFF
           ORDER BY SALE_ID);
    RETURN TABLE(RS);
END
CALL TABLED_T151(80);
Result3 rows · 2 columns
SALE_IDTHE_AMOUNT
1100.00
2250.50
4310.00

Three rows, the ones over the cutoff we passed in.

Now a question worth asking. The procedure is gone the moment that statement ended. Can the next statement still get at those rows?

Query
SELECT SALE_ID, THE_AMOUNT FROM TABLE(RESULT_SCAN(LAST_QUERY_ID()))
ORDER BY SALE_ID;
Result3 rows · 2 columns
SALE_IDTHE_AMOUNT
1100.00
2250.50
4310.00

The same three rows, and there is no procedure named anywhere in that query. So the rows outlive the procedure even though the name does not.

Hold on to that, because it is where this post is going.

Can a CTE and a procedure share one WITH clause?

A WITH clause already holds CTEs, so this is a fair question. Let's put a CTE first and then a procedure that counts its rows.

Query
WITH BIG_ONES AS (
    SELECT SALE_ID, AMOUNT FROM SALES_T151 WHERE AMOUNT > 80
),
COUNTER_T151 AS PROCEDURE ()
RETURNS NUMBER
LANGUAGE SQL
AS
DECLARE
    HOW_MANY NUMBER;
BEGIN
    SELECT COUNT(*) INTO :HOW_MANY FROM BIG_ONES;
    RETURN :HOW_MANY;
END
CALL COUNTER_T151();
Query failed — Snowflake returned an error
002003 (42S02): Uncaught exception of type 'STATEMENT_ERROR' on line 4 at position 4 : SQL compilation error:
Object 'BIG_ONES' does not exist or not authorized. Your primary role ACCOUNTADMIN or one of your secondary roles must have at least one privilege granted on TABLE BIG_ONES.

002003, the object does not exist. So the procedure body cannot see its neighbour in the same WITH clause.

And that is not the CTE being broken. On its own it behaves exactly the way Level 4 taught it.

Query
WITH BIG_ONES AS (
    SELECT SALE_ID, AMOUNT FROM SALES_T151 WHERE AMOUNT > 80
)
SELECT COUNT(*) AS HOW_MANY FROM BIG_ONES;
Result1 row · 1 column
HOW_MANY
3

Now the same two the other way round. Read the body carefully, because it counts the table and not the CTE.

Query
WITH COUNTER2_T151 AS PROCEDURE ()
RETURNS NUMBER
LANGUAGE SQL
AS
DECLARE
    HOW_MANY NUMBER;
BEGIN
    SELECT COUNT(*) INTO :HOW_MANY FROM SALES_T151;
    RETURN :HOW_MANY;
END,
BIG_ONES AS (
    SELECT SALE_ID FROM SALES_T151 WHERE AMOUNT > 80
)
CALL COUNTER2_T151();
Result1 row · 1 column
COUNTER2_T151
5

Created and called with no complaint. So the two can share one WITH clause perfectly happily.

What the body cannot do is see the CTE. That is about scope, not about which one you write first, and this run did not test the order on its own.

And the statement after it does not have to be a call

Query
WITH UNUSED_T151 AS PROCEDURE ()
RETURNS NUMBER
LANGUAGE SQL
AS
BEGIN
    RETURN 1;
END
SELECT COUNT(*) AS HOW_MANY FROM SALES_T151;
Result1 row · 1 column
HOW_MANY
5

The procedure was declared and never called, and the SELECT ran as if the WITH clause were not there.

And two procedures in one WITH clause?

Let's declare two, separated by a comma, and call the second one.

Query
WITH HALF_T151 AS PROCEDURE (N NUMBER)
RETURNS NUMBER
LANGUAGE SQL
AS
BEGIN
    RETURN :N / 2;
END,
QUARTER_T151 AS PROCEDURE (N NUMBER)
RETURNS NUMBER
LANGUAGE SQL
AS
BEGIN
    RETURN :N / 4;
END
CALL QUARTER_T151(100);
Result1 row · 1 column
QUARTER_T151
25.000000

A quarter of a hundred. So both of them were declared, and the one we named is the one that ran. The trailing zeros are what dividing a NUMBER hands back.

But can one of them call the other? Let's write one that calls its neighbour and reads the answer back.

Query
WITH INNER_T151 AS PROCEDURE (N NUMBER)
RETURNS NUMBER
LANGUAGE SQL
AS
BEGIN
    RETURN :N * 2;
END,
OUTER_T151 AS PROCEDURE (N NUMBER)
RETURNS NUMBER
LANGUAGE SQL
AS
DECLARE
    THE_ANSWER NUMBER;
BEGIN
    CALL INNER_T151(:N);
    SELECT INNER_T151 INTO :THE_ANSWER FROM TABLE(RESULT_SCAN(LAST_QUERY_ID()));
    RETURN :THE_ANSWER + 1;
END
CALL OUTER_T151(10)
Query failed — Snowflake returned an error
002139 (02000): Uncaught exception of type 'STATEMENT_ERROR' on line 4 at position 4 : SQL compilation error:
Unknown function INNER_T151.

No. Unknown function again. They cannot see each other any more than they can see a CTE.

Now the part this post is built around

Let's write an anonymous procedure that inserts a row.

Query
WITH WRITER_T151 AS PROCEDURE ()
RETURNS VARCHAR
LANGUAGE SQL
AS
BEGIN
    INSERT INTO SALES_T151 (SALE_ID, REGION, AMOUNT)
        VALUES (90, 'anon', 7.00);
    RETURN 'wrote a row';
END
CALL WRITER_T151();
Result1 row · 1 column
WRITER_T151
wrote a row

It wrote a row. And by the time that message came back the procedure was already gone.

So here is the question. Is the row gone with it? Let's go and look for it.

Query
SELECT SALE_ID, REGION, AMOUNT FROM SALES_T151 WHERE SALE_ID = 90;
Result1 row · 3 columns
SALE_IDREGIONAMOUNT
90anon7.00

There it is, still in the table.

The thing to take away

The definition lasted one statement. What it did is permanent. There is nothing in the catalog to tell you that row was ever written by a procedure, because there was never a procedure to tell you about.

Which is the whole reason this shape exists. For a one-off job you do not want to leave a procedure behind, and this leaves none.

Whose privileges does it run with?

Let's ask it directly, with EXECUTE AS CALLER written out.

Query
WITH ASCALLER_T151 AS PROCEDURE ()
RETURNS VARCHAR
LANGUAGE SQL
EXECUTE AS CALLER
AS
BEGIN
    RETURN 'running as ' || CURRENT_ROLE();
END
CALL ASCALLER_T151();
Result1 row · 1 column
ASCALLER_T151
running as ACCOUNTADMIN

That is the role the session was using, so it ran as the caller.

Now let's try to say EXECUTE AS OWNER instead.

Query
WITH ASOWNER_T151 AS PROCEDURE ()
RETURNS VARCHAR
LANGUAGE SQL
EXECUTE AS OWNER
AS
BEGIN
    RETURN 'running as ' || CURRENT_ROLE();
END
CALL ASOWNER_T151()
Query failed — Snowflake returned an error
090274 (42601): Anonymous procedures are callers rights only. Explicitly setting this property is not needed.

090274, and that message is better than any explanation I could write. There is no owner, because nothing was ever created.

Can the body be another language?

The body has been SQL so far. Let's try JavaScript in the same shape.

Query
WITH JSPROC_T151 AS PROCEDURE (N FLOAT)
RETURNS FLOAT
LANGUAGE JAVASCRIPT
AS
$$
    return N * 2;
$$
CALL JSPROC_T151(21);
Result1 row · 1 column
JSPROC_T151
42.0

Forty two, as a float. So the form takes a JavaScript body with no trouble at all.

Now Python, in the same shape.

Query
WITH PYPROC_T151 AS PROCEDURE (N FLOAT)
RETURNS FLOAT
LANGUAGE PYTHON
RUNTIME_VERSION = '3.11'
HANDLER = 'f'
AS
$$
def f(n):
    return n * 2
$$
CALL PYPROC_T151(21)
Query failed — Snowflake returned an error
100357 (P0000): Python Interpreter Error:
ModuleNotFoundError: No module named 'snowflake.snowpark' in function PYPROC_T151 with handler f

A module-not-found error. Now read where that error came from. It says Python interpreter error and it names our handler, so the statement was accepted and the handler actually ran.

What it tripped on is a package a Python procedure needs, and the declaration above does not ask for one. That is an omission in what we wrote, not a limit of the form.

So this grid tells us Python gets as far as the interpreter, and nothing beyond that. We are not going to claim more than it shows.

One last thing: the arguments are checked the usual way

Let's declare one that takes a single argument and call it with two.

Query
WITH ARITY_T151 AS PROCEDURE (N NUMBER)
RETURNS NUMBER
LANGUAGE SQL
AS
BEGIN
    RETURN :N;
END
CALL ARITY_T151(1, 2);
Query failed — Snowflake returned an error
000939 (22023): SQL compilation error: error line 0 at position -1
too many arguments for function [ARITY_T151(1, 2)] expected 1, got 2

Too many arguments, and it says what it expected and what it got. Nothing special about anonymous procedures here. The arity is checked the same way it is for any function.

And the clean-up, which is almost nothing

There is one table to drop, and that is it.

Query
DROP TABLE IF EXISTS DEMO_DB.PUBLIC.SALES_T151;
Result1 row · 1 column
status
SALES_T151 successfully dropped.

Now the checks afterwards.

Query
SELECT CURRENT_DATABASE()    AS THE_DATABASE,
       CURRENT_SCHEMA()      AS THE_SCHEMA,
       CURRENT_TRANSACTION() AS ANY_OPEN_TRANSACTION;
Result1 row · 3 columns
THE_DATABASETHE_SCHEMAANY_OPEN_TRANSACTION
DEMO_DBPUBLICNULL
Query
SHOW PROCEDURES LIKE '%\\_T151';
Result0 rows · 16 columns · scroll →
created_onnameschema_nameis_builtinis_aggregateis_ansimin_num_argumentsmax_num_argumentsargumentsdescriptioncatalog_nameis_table_functionvalid_for_clusteringis_securesecretsexternal_access_integrations
Query
SELECT COUNT(*) AS PROBE_TABLES_LEFT
FROM DEMO_DB.INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'PUBLIC' AND ENDSWITH(TABLE_NAME, '_T151');
Result1 row · 1 column
PROBE_TABLES_LEFT
0

Same database and schema, nothing open, an empty grid where the procedures would be, and no tables left. The empty grid is the point of the whole post.

Key points

  • An anonymous procedure is WITH, a name, AS PROCEDURE, the body, and then the statement that uses it. All one statement, and no CREATE anywhere.
  • The body can be wrapped in $$ or written bare. Both work.
  • RETURNS is not optional, and the body has to be a block. Those are 092226 and 001003.
  • Nothing goes in the catalog. SHOW PROCEDURES finds nothing, calling the name on its own line is 002139, and a DROP reports it was already dropped.
  • The call has to name the procedure you just declared, and a WITH clause with nothing after it is not a statement.
  • Inside the body you get the whole language: a DECLARE section, a loop, an exception handler, and a RESULTSET handed back with RETURN TABLE.
  • The next statement can read those rows back with RESULT_SCAN. The rows outlive the name.
  • A CTE and a procedure can share one WITH clause, but the body cannot see the CTE.
  • Two procedures can share one WITH clause, and neither can call the other.
  • A row an anonymous procedure wrote is still there after the procedure has gone. The definition lasts one statement. What it did is permanent.
  • It is always the caller's rights. EXECUTE AS OWNER is 090274, because there is no owner.
  • A JavaScript body works in the same form. The Python one here reached the interpreter and stopped on a package it was never given.
  • Too many arguments is 000939, checked the same way as for any function.
Next in this series

In the next post we stop running things and start reading plans: EXPLAIN. What the steps mean, what the partition columns are telling you, and a count that proves EXPLAIN did not run the query.

Every query, every result grid and every error pane on this page was captured from a live Snowflake account (version 10.35.101) running the demo script for this episode. Four of the statements above are shown without the demo file's own banner comment, which the capture swept up because an anonymous procedure has no terminator; nothing else about any statement was changed, and the error panes are printed exactly as they came back. Every count in the text is read off one of the grids on this page. No account identifier, user name or query id appears anywhere on this page. Nothing is timed and no performance claims are made anywhere in this series. Behaviour follows the Snowflake anonymous procedures documentation.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.