User-defined functions are the quiet workhorse of Snowflake engineering. When a built-in function does not exist, a Python UDF lets you push custom logic to the data instead of pulling data out. This tutorial covers the three shapes you will use most: scalar UDFs, vectorized UDFs, and user-defined table functions (UDTFs).
Choosing the right tool
| Need | Use |
|---|---|
| Simple expression reuse | SQL UDF (fastest, optimizer-friendly) |
| Row-by-row custom logic or a library | Python scalar UDF |
| Heavy numeric or pandas logic on many rows | Vectorized Python UDF |
| One row in, many rows out, or per-partition logic | UDTF |
| Multi-step side effects, DDL | Stored procedure, not a UDF |
Rule of thumb: start with SQL, move to Python only when you need a library or logic SQL cannot express.
A scalar Python UDF
CREATE OR REPLACE FUNCTION clean_phone(raw STRING)
RETURNS STRING
LANGUAGE PYTHON
RUNTIME_VERSION = '3.11'
HANDLER = 'run'
AS $$
import re
def run(raw):
if raw is None:
return None
digits = re.sub(r'\D', '', raw)
return digits[-10:] if len(digits) >= 10 else None
$$;
SELECT clean_phone(phone) FROM customers;
Handle NULLs explicitly. Add RETURNS NULL ON NULL INPUT if you want Snowflake to skip the call for NULL arguments.
Vectorized UDFs
Scalar UDFs are invoked per row. A vectorized UDF receives batches as a pandas Series or DataFrame, which cuts call overhead dramatically for numeric work.
CREATE OR REPLACE FUNCTION zscore(x FLOAT, mean FLOAT, sd FLOAT)
RETURNS FLOAT
LANGUAGE PYTHON
RUNTIME_VERSION = '3.11'
PACKAGES = ('pandas')
HANDLER = 'compute'
AS $$
import pandas
from _snowflake import vectorized
@vectorized(input=pandas.DataFrame)
def compute(df):
return (df[0] - df[1]) / df[2]
$$;
Columns arrive positionally (df[0], df[1], ...). You can cap batch size with MAX_BATCH_ROWS in the function definition when memory is tight.
UDTFs: one row in, many rows out
CREATE OR REPLACE FUNCTION split_tags(tags STRING)
RETURNS TABLE (tag STRING, position INT)
LANGUAGE PYTHON
RUNTIME_VERSION = '3.11'
HANDLER = 'Splitter'
AS $$
class Splitter:
def process(self, tags):
if tags:
for i, t in enumerate(tags.split(',')):
yield (t.strip(), i)
$$;
SELECT o.order_id, t.tag
FROM orders o, TABLE(split_tags(o.tags)) t;
Partition-aware UDTFs
A UDTF handler can also implement end_partition, which runs after all rows of a partition were passed to process. This enables per-group logic such as sessionization or fitting a small model per customer.
CREATE OR REPLACE FUNCTION partition_total(amount NUMBER)
RETURNS TABLE (total NUMBER)
LANGUAGE PYTHON
RUNTIME_VERSION = '3.11'
HANDLER = 'Summer'
AS $$
class Summer:
def __init__(self):
self.s = 0
def process(self, amount):
self.s += amount or 0
return []
def end_partition(self):
yield (self.s,)
$$;
SELECT customer_id, t.total
FROM payments,
TABLE(partition_total(amount) OVER (PARTITION BY customer_id)) t;
Keep partitions reasonably sized, since a partition is processed on one node and a skewed key can cause memory pressure.
Packages and imports
PACKAGES = ('numpy','scikit-learn')pulls from the Snowflake Anaconda channel with no install step.- For your own code, upload a zip or
.pyto a stage and reference it withIMPORTS = ('@code_stage/helpers.py'). - Pin versions where reproducibility matters, for example
'pandas==2.2.*'. - Calling the internet needs an external access integration; see our tutorial on external access.
Performance checklist
- Load heavy objects (models, lookup tables) once at module level or in
__init__, not inside the per-row path. - Prefer vectorized UDFs for arithmetic and pandas-friendly logic.
- Filter before calling the function so fewer rows hit Python.
- Check the Query Profile; a Python UDF node taking most of the time means it is a candidate for a SQL rewrite.
- Use a larger warehouse only after fixing the above, since UDF work scales with rows and parallelism, not warehouse magic.
Governance and deployment
- Grant
USAGEon functions through access roles, and useSECUREfunctions when sharing logic through data sharing so the body stays hidden. - Keep definitions in Git and deploy with
CREATE OR ALTERor your CI/CD pipeline. - Add unit tests by extracting handler logic into plain Python modules you can test locally before registering.
Common pitfalls
- Forgetting NULL handling and returning errors on a single bad row. Return None or catch exceptions.
- Non-deterministic functions (random, time) marked as IMMUTABLE. Leave the default VOLATILE unless the output is truly stable.
- Using a UDF when a built-in exists, which blocks optimizer pushdown.
Need a hand?
PowderInsights Snowflake developers build and tune UDF libraries, Snowpark pipelines, and full data platforms. If you have a project or a role to staff, get in touch through our contact page.