Skip to main content
πŸ“–

Key Terms β€” Functions & Procedures

User-Defined Function

UDF

A custom scalar function that returns a single value per input row. Can be written in SQL, JavaScript, Python, or Java.

User-Defined Table Function

UDTF

A custom function that returns a set of rows (a table). Called with TABLE() in the FROM clause.

SP

Stored Procedure

A procedural block that can perform DDL/DML, control flow, and return a single value. Supports SQL, JavaScript, Python, Java, and Scala.

β€”

External Function

A UDF that calls an external API (via API Gateway + Lambda/Cloud Function). Snowflake sends data out and receives results back.

β€”

Owner's Rights

Default for stored procedures β€” executes with the privileges of the procedure owner, not the caller.

β€”

Caller's Rights

Optional mode where the procedure executes with the caller's privileges. Set with EXECUTE AS CALLER.


UDFs (User-Defined Functions)

UDFs are scalar functions β€” they take input values and return a single value per row. They are used in SELECT, WHERE, and other expression contexts.

SQL UDF
1-- Simple SQL UDF
2CREATE OR REPLACE FUNCTION mask_email(email VARCHAR)
3RETURNS VARCHAR
4LANGUAGE SQL
5AS
6$$
7CONCAT(LEFT(email, 2), '****@', SPLIT_PART(email, '@', 2))
8$$;
9
10-- Usage
11SELECT mask_email('john.smith@company.com');
12-- Result: jo****@company.com
JavaScript UDF
1-- JavaScript UDF
2CREATE OR REPLACE FUNCTION calculate_bmi(weight_kg FLOAT, height_m FLOAT)
3RETURNS FLOAT
4LANGUAGE JAVASCRIPT
5AS
6$$
7return WEIGHT_KG / (HEIGHT_M * HEIGHT_M);
8$$;
9
10-- Note: JavaScript UDFs receive column names in UPPERCASE
Python UDF
1-- Python UDF (requires Snowpark)
2CREATE OR REPLACE FUNCTION sentiment_score(text VARCHAR)
3RETURNS FLOAT
4LANGUAGE PYTHON
5RUNTIME_VERSION = '3.8'
6HANDLER = 'score'
7AS
8$$
9def score(text):
10 positive = ['good', 'great', 'excellent', 'love']
11 words = text.lower().split()
12 matches = sum(1 for w in words if w in positive)
13 return matches / max(len(words), 1)
14$$;
🎯Exam Focus: UDF Languages

UDFs support SQL, JavaScript, Python, and Java. JavaScript UDFs receive column names in UPPERCASE. Python UDFs require specifying RUNTIME_VERSION and HANDLER. SQL UDFs are the simplest and most performant.


UDTFs (User-Defined Table Functions)

UDTFs return a set of rows rather than a single value. They are called using TABLE() in the FROM clause.

JavaScript UDTF
1-- UDTF that splits a string into rows
2CREATE OR REPLACE FUNCTION split_to_rows(input VARCHAR, delimiter VARCHAR)
3RETURNS TABLE (value VARCHAR, position INT)
4LANGUAGE JAVASCRIPT
5AS
6$$
7{
8processRow: function(row, rowWriter, context) {
9 var parts = row.INPUT.split(row.DELIMITER);
10 for (var i = 0; i < parts.length; i++) {
11 rowWriter.writeRow({VALUE: parts[i].trim(), POSITION: i + 1});
12 }
13}
14}
15$$;
16
17-- Usage: call with TABLE() and OVER()
18SELECT t.value, t.position
19FROM TABLE(split_to_rows('apple,banana,cherry', ',')) AS t;
ℹ️UDTF vs FLATTEN

For simple array/object expansion, use the built-in FLATTEN function. UDTFs are for custom row-generating logic that FLATTEN cannot handle.


Stored Procedures

Stored procedures can execute DDL, DML, and control flow logic. Unlike UDFs, they are not called in expressions β€” you invoke them with CALL.

SQL Stored Procedure
1-- SQL Scripting stored procedure
2CREATE OR REPLACE PROCEDURE archive_old_orders(cutoff_date DATE)
3RETURNS VARCHAR
4LANGUAGE SQL
5AS
6$$
7BEGIN
8INSERT INTO sales.orders_archive
9SELECT * FROM sales.orders WHERE order_date < :cutoff_date;
10
11DELETE FROM sales.orders WHERE order_date < :cutoff_date;
12
13RETURN 'Archive complete';
14END;
15$$;
16
17-- Call the procedure
18CALL archive_old_orders('2023-01-01');
JavaScript Stored Procedure
1-- JavaScript stored procedure with error handling
2CREATE OR REPLACE PROCEDURE refresh_summary(schema_name VARCHAR)
3RETURNS VARCHAR
4LANGUAGE JAVASCRIPT
5EXECUTE AS OWNER
6AS
7$$
8try {
9 var stmt = snowflake.createStatement({
10 sqlText: 'TRUNCATE TABLE ' + SCHEMA_NAME + '.daily_summary'
11 });
12 stmt.execute();
13
14 stmt = snowflake.createStatement({
15 sqlText: 'INSERT INTO ' + SCHEMA_NAME + '.daily_summary SELECT * FROM ' + SCHEMA_NAME + '.v_daily_summary'
16 });
17 var result = stmt.execute();
18 return 'Refreshed ' + result.getNumRowsInserted() + ' rows';
19} catch (err) {
20 return 'Error: ' + err.message;
21}
22$$;

UDF vs Stored Procedure

UDF vs Stored Procedure

Feature
UDF (Function)
Stored Procedure
Returns
A value per row (scalar) or rows (UDTF)
A single value (status/result)
Usage
In SELECT, WHERE, expressions
CALL statement only
DDL/DML
Cannot execute DDL or DML
βœ“Can execute DDL and DML
Side effects
No side effects β€” pure function
Can modify data and objects
Transaction
Runs within caller's transaction
βœ“Can manage its own transactions
Languages
SQL, JavaScript, Python, Java
βœ“SQL, JavaScript, Python, Java, Scala
🎯Exam Focus: When to Use Which

UDF: custom calculations, transformations, data masking β€” used in queries. Stored Procedure: ETL orchestration, admin tasks, DDL operations β€” called independently with CALL. The exam frequently tests this distinction.


Owner’s Rights vs Caller’s Rights

Owner's vs Caller's Rights

Feature
Owner's Rights (Default)
Caller's Rights
Privileges used
Procedure owner's privileges
Calling user's privileges
Syntax
EXECUTE AS OWNER (default)
EXECUTE AS CALLER
Security
βœ“Caller does not need direct table access
Caller must have all required privileges
Use case
Controlled data access, encapsulation
User-context operations, session variables
Applies to
Stored procedures only
Stored procedures only
πŸ”‘UDFs Are Always Caller's Rights

UDFs always run with the caller’s privileges. Only stored procedures support the Owner’s Rights / Caller’s Rights distinction.


External Functions

External functions call an external API outside Snowflake. Data is sent to an API Gateway (AWS API Gateway, Azure API Management, or GCP API Gateway) which forwards to a Lambda/Cloud Function.

External Function Architecture

Flow: 1) Snowflake sends rows to API Integration endpoint. 2) API Gateway (AWS API Gateway / Azure APIM / GCP API Gateway) receives the request. 3) Gateway forwards to compute service (Lambda / Azure Function / Cloud Function). 4) Compute processes data and returns results. 5) Results flow back through API Gateway to Snowflake. All communication is HTTPS.

Flow from Snowflake through API Gateway to cloud function and back
Creating an External Function
1-- Step 1: Create API integration
2CREATE API INTEGRATION my_api_integration
3API_PROVIDER = aws_api_gateway
4API_AWS_ROLE_ARN = 'arn:aws:iam::123456789:role/my-role'
5API_ALLOWED_PREFIXES = ('https://abc123.execute-api.us-east-1.amazonaws.com/')
6ENABLED = TRUE;
7
8-- Step 2: Create the external function
9CREATE EXTERNAL FUNCTION translate_text(text VARCHAR, target_lang VARCHAR)
10RETURNS VARCHAR
11API_INTEGRATION = my_api_integration
12AS 'https://abc123.execute-api.us-east-1.amazonaws.com/prod/translate';
13
14-- Step 3: Use like any function
15SELECT translate_text(description, 'fr') FROM products;
⚠️External Function Limitations

External functions are slower than native UDFs due to network latency. Data leaves Snowflake β€” consider security implications. They are billed per row processed and have rate limits.


Cheat Sheet

πŸ“‹
Quick Reference

Functions & Procedures Quick Reference

πŸ”§
UDFs
Type
Scalar (one value per row) or tabular (UDTF)
Languages
SQL, JavaScript, Python, Java
Usage
In SELECT, WHERE, JOIN conditions
Rights
Always caller's rights
βš™οΈ
Stored Procedures
Languages
SQL, JavaScript, Python, Java, Scala
Invocation
CALL procedure_name(args)
Default rights
Owner's rights (EXECUTE AS OWNER)
Can do DDL/DML
Yes β€” CREATE, INSERT, DELETE, etc.
🌐
External Functions
Mechanism
API Integration + API Gateway + Cloud Function
Transport
HTTPS (data leaves Snowflake)
Performance
Slower due to network round-trip

Practice Quiz

Transformations

Which of the following can a stored procedure do that a UDF cannot?

Transformations

What is the default execution mode for stored procedures?

Transformations

How do you call a UDTF in a query?


Flashcards

Transformations
QUESTION

What languages can Snowflake UDFs be written in?

Click to reveal answer
ANSWER

SQL, JavaScript, Python, and Java. JavaScript UDFs receive column names in UPPERCASE. Python UDFs require RUNTIME_VERSION and HANDLER parameters.

Click to see question
Transformations
QUESTION

What is the difference between a UDF and a stored procedure?

Click to reveal answer
ANSWER

UDFs return values and are used in queries (SELECT/WHERE). Stored procedures are called with CALL, can execute DDL/DML, and manage transactions. UDFs cannot modify data; stored procedures can.

Click to see question
Transformations
QUESTION

What are Owner's Rights vs Caller's Rights?

Click to reveal answer
ANSWER

Owner's Rights (default): procedure runs with the owner's privileges β€” caller does not need direct access to underlying objects. Caller's Rights (EXECUTE AS CALLER): runs with the caller's privileges. Only applies to stored procedures β€” UDFs are always caller's rights.

Click to see question
Transformations
QUESTION

How do external functions work in Snowflake?

Click to reveal answer
ANSWER

Snowflake sends data via HTTPS to an API Gateway (AWS/Azure/GCP), which forwards to a cloud function (Lambda/Azure Function). Results are returned the same way. Requires an API Integration object. Data leaves Snowflake, so consider security.

Click to see question
Transformations
QUESTION

When should you use a UDTF instead of a UDF?

Click to reveal answer
ANSWER

Use a UDTF when you need to return multiple rows per input row (one-to-many). UDFs return exactly one value per input row (one-to-one). UDTFs are called with TABLE() in the FROM clause.

Click to see question

Resources


Next Steps

Reinforce what you just read

Study the All flashcards with spaced repetition to lock it in.

Study flashcards β†’