How it works
Snowflake offers seven distinct UDF execution shapes that all register under the same CREATE FUNCTION statement but resolve to very different runtimes inside the execution layer.
The engineering decision that drives every UDF design is whether the function body can be inlined into the query plan or must be shipped to a worker sandbox. SQL UDFs inline. Everything else pays a sandbox tax on every row.
That distinction governs which UDF kind is appropriate for a given workload and how it interacts with pruning, clustering, caching, and the secure variant of the same function.
- A scalar UDF returns one value per input row.
- A UDTF (User-Defined Table Function) returns a set of rows per input row, with a row-by-row PROCESS method and an optional ENDPARTITION finalizer in handler-based languages.
- A UDAF (User-Defined Aggregate Function) accumulates state across many rows and emits a single value per group, requiring an initialization step, an accumulation step, a merge step for parallel partial aggregates, and a finalize step.
UDTFs and UDAFs are intentionally rigid in their handler contracts: missing one of the lifecycle methods raises a runtime error at first invocation, not at CREATE time.
SQL UDFs
SQL UDFs are stored as parsed expression trees.
The optimizer can inline a SQL UDF directly into the surrounding query plan, which means a scalar SQL UDF preserves constant folding, predicate pushdown, and micro-partition pruning.
If you wrap WHERE event_ts > '2024-01-01' inside a SQL UDF and the optimizer recognizes the constant boundary, pruning still happens.
The same logic in a Python UDF stops pruning because the function body is opaque to the planner.
CREATE OR REPLACE FUNCTION ANALYTICS_DB.ENG_SCHEMA.NORMALIZE_EMAIL(raw STRING)
RETURNS STRING
LANGUAGE SQL
IMMUTABLE
AS
$
LOWER(TRIM(REGEXP_REPLACE(raw, '\\s+', '')))
$;
SELECT ANALYTICS_DB.ENG_SCHEMA.NORMALIZE_EMAIL(' Alice@Example.COM ');
A SQL UDF that returns a table is a SQL UDTF, defined with RETURNS TABLE(...). SQL UDTFs are particularly efficient because they participate in join planning. A common pattern is to expose a parameterized lookup as a table function joined with LATERAL.
CREATE OR REPLACE FUNCTION ANALYTICS_DB.ENG_SCHEMA.ORDERS_FOR_CUSTOMER(cust_id NUMBER)
RETURNS TABLE(order_id NUMBER, order_ts TIMESTAMP_NTZ, total NUMBER(18,2))
AS
$
SELECT o.order_id, o.order_ts, o.total
FROM ANALYTICS_DB.ENG_SCHEMA.ORDERS o
WHERE o.customer_id = cust_id
$;
SELECT c.customer_id, o.order_id, o.total
FROM ANALYTICS_DB.ENG_SCHEMA.CUSTOMERS c,
LATERAL ANALYTICS_DB.ENG_SCHEMA.ORDERS_FOR_CUSTOMER(c.customer_id) o;
JavaScript UDFs
JavaScript UDFs run in a sandboxed V8 process, one process per worker, with restricted access (no network, no file system, no setTimeout).
JavaScript is the only Snowflake language that exposes the typed array marshaling needed for some VARIANT manipulation patterns.
Numbers above 2^53 lose precision because JavaScript stores them as IEEE 754 doubles, so any NUMBER value passed to a JavaScript UDF must be received as a string when high precision is required.
CREATE OR REPLACE FUNCTION ANALYTICS_DB.ENG_SCHEMA.FLATTEN_TAGS(payload VARIANT)
RETURNS ARRAY
LANGUAGE JAVASCRIPT
AS
$
const out = [];
const tags = PAYLOAD.tags || {};
Object.keys(tags).forEach(k => out.push({ key: k, value: String(tags[k]) }));
return out;
$;
Snowpark UDFs (Python, Java, Scala)
Snowpark UDFs ship a serialized callable into a language-specific sandbox: CPython for Python, JVM for Java and Scala. The sandbox imposes egress restrictions; outbound network access is denied unless the function is created with an EXTERNAL ACCESS INTEGRATION and one or more NETWORK RULE objects. The sandbox does allow imports from staged packages and from the Snowflake Anaconda channel for Python.
from snowflake.snowpark import Session
from snowflake.snowpark.functions import udf
from snowflake.snowpark.types import StringType, IntegerType
session = Session.builder.config("connection_name", "default").create()
@udf(name="ANALYTICS_DB.ENG_SCHEMA.MASK_PHONE",
is_permanent=True,
stage_location="@ANALYTICS_DB.ENG_SCHEMA.UDF_STAGE",
replace=True,
packages=["snowflake-snowpark-python"],
return_type=StringType(),
input_types=[StringType()])
def mask_phone(raw: str) -> str:
if raw is None or len(raw) < 4:
return None
return "X" * (len(raw) - 4) + raw[-4:]
Vectorized Python UDFs accept a pandas DataFrame batch and return a Series, decorated with @udf(input_types=[...], return_type=..., max_batch_size=N) and the additional argument packages=["pandas"].
Vectorization typically yields a five to twenty times speedup on numeric and string workloads because per-row Python interpreter overhead drops to per-batch overhead.
Use vectorized form for any UDF that processes more than a few million rows per call.
Java and Scala UDFs use a handler class with a method whose signature is described in the CREATE FUNCTION statement.
The compiled JAR is staged, and the handler is referenced as <package>.<class>.<method>.
The JVM is shared across invocations on a worker, so static initializers run once and may hold expensive objects (compiled regex, ML model state) without repeated cost.
CREATE OR REPLACE FUNCTION ANALYTICS_DB.ENG_SCHEMA.PARSE_USER_AGENT(ua STRING)
RETURNS OBJECT
LANGUAGE JAVA
RUNTIME_VERSION = '11'
IMPORTS = ('@ANALYTICS_DB.ENG_SCHEMA.UDF_STAGE/ua-parser-1.5.4.jar')
HANDLER = 'com.acme.ua.Parser.parse';
UDTFs
A UDTF in Python implements a class with process(self, *args) returning an iterable of tuples or yielding tuples, and optionally end_partition(self) to emit a final aggregation per partition. Specifying PARTITION BY in the calling SQL hands each partition to a fresh handler instance, which is mandatory for stateful UDTFs.
from snowflake.snowpark.functions import udtf
from snowflake.snowpark.types import StructType, StructField, StringType, IntegerType
class SessionSplitter:
def __init__(self):
self.prev_ts = None
self.session_id = 0
def process(self, ts, user_id):
if self.prev_ts is None or (ts - self.prev_ts).total_seconds() > 1800:
self.session_id += 1
self.prev_ts = ts
yield (user_id, self.session_id, ts)
session.udtf.register(
SessionSplitter,
output_schema=StructType([
StructField("USER_ID", StringType()),
StructField("SESSION_ID", IntegerType()),
StructField("EVENT_TS", StringType())]),
input_types=[StringType(), StringType()],
name="ANALYTICS_DB.ENG_SCHEMA.SESSION_SPLITTER",
is_permanent=True,
stage_location="@ANALYTICS_DB.ENG_SCHEMA.UDF_STAGE",
replace=True)
UDAFs
A Python UDAF implements four methods: __init__, accumulate(value), merge(other_state), and finish(). The aggregate_state property optionally serializes intermediate state for partial-aggregate parallelism. UDAFs are the only mechanism to write custom GROUP BY logic that the engine will partition and merge across workers correctly. Java UDAFs follow the same contract with a class implementing the AggregateHandler interface.
Secure UDFs
Adding SECURE to the CREATE FUNCTION statement marks the function as secure, which has two consequences.
- First, the function definition is hidden from users who do not own the function:
GET_DDLreturns redacted source andINFORMATION_SCHEMA.FUNCTIONShides the body column. - Second, the optimizer disables predicate pushdown and other plan rewrites that could let a caller infer the function body by timing or by selectively querying intermediate results.
Secure functions are required for any function that crosses a data share boundary, because the function body would otherwise be exposed to share consumers.
💡 Exam Trap: A scalar SQL UDF marked
SECUREloses inlining and pruning, which can multiply scan cost by orders of magnitude. Mark UDFsSECUREonly when they are exposed across share boundaries or when a column-masking policy applies, not as a generic hardening setting.
📊 Limit: A single UDF or UDTF call must complete within the warehouse statement timeout (default 172800 seconds, configurable per warehouse and per session). A vectorized Python UDF's
max_batch_sizedefaults to engine-chosen but can be set up to 65535 rows per batch.
⚠️ Anti-Pattern: Using a Python UDF inside a WHERE clause on a multi-billion row table eliminates pruning, forces a full table scan, and burns warehouse credits proportional to total data, not selected data. Rewrite as a SQL UDF or pre-compute the predicate as a column.
🎯 Scenario: A retail platform stores customer phone numbers in a wide fact table and exposes a Secure UDF
MASK_PHONEto a shared dataset for a partner. The team reports that share consumers cannot read the function body, but warehouse credit consumption spikes when partners query the share. The cause is the optimizer disabling pushdown on secure functions; the resolution is to materialize the masked value into a derived column inside a regular table protected by a row access policy, then expose that table over the share without invoking the function inline.
Decision Anchor. Choose a SQL UDF when the logic can be expressed in SQL and inlining preserves pushdown. Choose a JavaScript UDF when you need lightweight, network-free row-level logic that is easy to inspect and does not require Python packages.
Choose a Snowpark Python UDF when you need pandas, scikit-learn, or any Anaconda-channel library and a vectorized batch interface. Choose a Java or Scala UDF when an existing JAR encapsulates the logic and you need JVM-level performance.
Choose a UDTF when one input row produces a variable number of output rows. Choose a UDAF when the engine's built-in aggregates do not cover the custom accumulation.
Choose SECURE only for share-exposed surfaces and masking policies, never as a default.
