Amazon Redshift UDFs let you encapsulate reusable SQL or Python logic as callable database functions.
A user-defined function (UDF) is custom code—written in SQL or Python—that you register once and reuse in any query, view, or dashboard. UDFs act like built-in functions but can include complex business rules that standard SQL lacks.
Use UDFs to centralize complicated CASE expressions, currency conversions, or machine-learning scores. Keeping logic in one place reduces copy-paste errors and speeds up query authoring.
Write the function body in standard Redshift SQL, define input parameters and a return type, and execute CREATE FUNCTION
.
CREATE [ OR REPLACE ] FUNCTION schema_name.fn_name(param_name param_type, ...)
RETURNS return_type
IMMUTABLE | STABLE | VOLATILE
AS $$
-- SQL statements
$$ LANGUAGE SQL;
Choose IMMUTABLE for deterministic logic like tax rates, STABLE for read-only queries, and VOLATILE for non-deterministic functions.
Python UDFs run in AWS Lambda-style containers. Add the plpythonu
language flag and write standard Python 3 code.
CREATE OR REPLACE FUNCTION public.format_currency(numeric)
RETURNS varchar
IMMUTABLE
AS $$
import locale
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
return locale.currency(args[0], grouping=True)
$$ LANGUAGE plpythonu;
Pack extra libraries into a ZIP and reference it with library_path
if needed.
Invoke it like any other function: SELECT schema_name.fn_name(arg1, arg2);
Use it in projections, WHERE clauses, GROUP BY, or ORDER BY.
Update code with CREATE OR REPLACE FUNCTION
. Remove it with DROP FUNCTION schema_name.fn_name(arg_type, ...);
—be sure to list parameter types.
utils
schema and grant EXECUTE to analysts.calc_margin_v2
) to avoid breaking dashboards.IMMUTABLE functions that query tables will silently return stale data. Python UDFs can slow queries if called per row—try set-based SQL UDFs first.
Add temporary RAISE NOTICE
statements in SQL UDFs or print()
in Python UDFs and query STL_UDF_LOG to view output.
No. Create overloads with different parameter lists instead.
No, they run only within the Redshift cluster.