Snowflake UDFs let you package reusable SQL or JavaScript logic as functions that run directly inside the warehouse.
UDFs centralize complex calculations—tax, discount, data cleansing—so every analyst reuses the same tested logic instead of copy-pasting SQL.
Use CREATE OR REPLACE FUNCTION
plus the function name, parameters, return type, and body. Bind your logic with RETURN
.
The code in the Example Query section shows a UDF that returns the discounted total for an order.
Call it like any built-in function: SELECT schema.udf_name(args);
. Combine it with joins, CTEs, or views for maximum reuse.
Yes. Swap LANGUAGE SQL
with LANGUAGE JAVASCRIPT
and wrap the body in $$ ... $$
. JavaScript UDFs handle loops and complex branching easily.
Keep UDFs small, deterministic, and well-commented. Store them in a dedicated schema like util
. Version them with CREATE OR REPLACE
scripts in Git.
Implicit casting: Always declare precise parameter types. Add ::NUMBER(38,2)
casts when mixing numeric scales.
Over-using JavaScript UDFs: SQL UDFs run faster because they leverage Snowflake’s vectorized engine. Reserve JavaScript for logic SQL cannot express.
They run inside standard warehouses, so charges equal the compute time you would pay for equivalent inline SQL.
Yes. Nesting is allowed, but keep call depth shallow to ease debugging.
Yes. UDFs inherit the privileges of the calling role. Limit access with GRANT EXECUTE
.
Use SELECT SYSTEM$GET_LAST_QUERY_ID()
after execution, then SHOW ERRORS
to inspect compilation details.