+1 (415) 997-4269

Python UDFs and UDTFs in Snowflake: Scalar, Vectorized, and Table Functions Done Right

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

NeedUse
Simple expression reuseSQL UDF (fastest, optimizer-friendly)
Row-by-row custom logic or a libraryPython scalar UDF
Heavy numeric or pandas logic on many rowsVectorized Python UDF
One row in, many rows out, or per-partition logicUDTF
Multi-step side effects, DDLStored 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 .py to a stage and reference it with IMPORTS = ('@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

  1. Load heavy objects (models, lookup tables) once at module level or in __init__, not inside the per-row path.
  2. Prefer vectorized UDFs for arithmetic and pandas-friendly logic.
  3. Filter before calling the function so fewer rows hit Python.
  4. Check the Query Profile; a Python UDF node taking most of the time means it is a candidate for a SQL rewrite.
  5. Use a larger warehouse only after fixing the above, since UDF work scales with rows and parallelism, not warehouse magic.

Governance and deployment

  • Grant USAGE on functions through access roles, and use SECURE functions when sharing logic through data sharing so the body stays hidden.
  • Keep definitions in Git and deploy with CREATE OR ALTER or 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.