CertSafari
    Snowflake SnowPro Advanced: Data Engineer (DEA-C02)· Lessons

    Domain 5 · Lesson 16/22

    Snowflake UDFs: types, handler languages and secure functions

    Define User-Defined Functions (UDFs) and outline how to use them.

    23 min read
    3.57% of exam
    9 sources
    Published 20 Oct 2026
    Docs as of 18 Oct 2026

    What you will be able to do

    • Pick between a scalar UDF, a UDTF and a UDAF from the shape of the input and output a calculation needs
    • Choose a handler language (SQL, JavaScript, Python, Java or Scala) from what the logic needs, and decide whether its code goes in-line or on a stage
    • Write a CREATE FUNCTION statement that brings in Anaconda packages through PACKAGES, or a compiled JAR through IMPORTS and a class-qualified HANDLER
    • Tell anonymous UDFs from named ones, and temporary from permanent, when registering through the Snowpark API
    • Explain what the SECURE keyword hides, what it leaves visible and what it costs in query performance

    Key concept

    Handler — The handler is the code that carries out a UDF's logic, written in SQL, JavaScript, Python, Java or Scala. CREATE FUNCTION wraps it in a name and a typed SQL signature. Callers only see that signature, so a UDF is called like a built-in function whatever language its handler uses.

    1.What a user-defined function is for

    A user-defined function (UDF) holds a calculation that Snowflake's built-in functions don't provide, so you can write it once and reuse it everywhere. A formula that turns a raw sensor reading into Celsius is a typical example. Without a UDF, every analyst copies the formula into their own queries, and each copy can drift. With one, the formula lives in a single object, and queries call it the same way they call UPPER or ROUND: in a SELECT list, a WHERE clause or a join condition.

    Every UDF has two parts. The handler is the logic, written in one of the supported languages. The CREATE FUNCTION statement gives that handler a name, typed arguments and a return type. Callers only see that SQL signature. As a result, the handler language makes no difference at the call site: a Python UDF and a SQL UDF are both called as name(args). Pick the language for what the logic needs, such as a library, existing compiled code or procedural statements. Whether SQL can call the function never depends on the language.

    A function always returns a value computed from its inputs, so a UDF is the right shape for "take these inputs, return that output." Two neighbouring objects handle other jobs. Stored procedures orchestrate several statements. External functions call a service outside Snowflake. A single reusable formula with no branching and no library needs neither. The lightest option is a SQL UDF whose body is just that expression.

    Checkpoint 1 of 11· Check yourself

    Analysts keep copying the same formula into their queries to convert raw sensor readings to Celsius. The team wants one shared definition that can be called in SELECT lists, WHERE clauses and join conditions. The formula needs no branching and no libraries. What should they create?

    Checkpoint 2 of 11· Exam question

    A data engineer wants to encapsulate a single repeated business calculation, converting a raw sensor reading to Celsius, so that every analyst-facing SQL query can call it as one reusable expression without duplicating the formula. No procedural branching or external library is required. Which approach fits this requirement best?

    Sources1

    2.Scalar UDFs, UDTFs and UDAFs

    Choose the UDF variation by comparing how many rows go in with how many come out. A plain UDF, also called a scalar function, returns one value per input row. A user-defined table function (UDTF) can return many rows for each input row, so you call it in the FROM clause and wrap it in TABLE(...). A user-defined aggregate function (UDAF) does the reverse: it reads many rows and returns one result, the way SUM or AVG does.

    The UDF variations and how each is called
    VariationRows in → rows outHow it is called
    Scalar UDFOne input row → one output row with a single valueLike a built-in, e.g. SELECT addone(3)
    UDTFOne input row → a tabular valueIn the FROM clause, e.g. SELECT * FROM TABLE(get_widgets_function())
    UDAFMany rows → one rowAs an aggregate, e.g. df.agg(sum_udaf("a"))
    Vectorized UDF / UDTFBatches of rows as Pandas DataFrames → Pandas arrays or Series, or tabular resultsPython handlers only

    A UDTF's handler sees its input in partitions. A Python UDTF handler is a class with a process method that Snowflake calls for each row. If the call includes a PARTITION BY clause, rows are grouped that way; if it doesn't, Snowflake still partitions the data on its own, so the handler must not assume it receives the whole table at once. If the partition has an ORDER BY, rows arrive at process in that order.

    UDAFs have the narrowest language support. When you create functions with SQL, only Python handlers can implement a UDAF. Java, JavaScript and SQL handlers support scalar UDFs and UDTFs, and a Scala handler created with SQL supports only a scalar UDF. If a question asks for a custom aggregate, the answer is a Python handler, whether you register it with the Snowpark API or create it with SQL.

    Checkpoint 3 of 11· Match them up

    Match each UDF variation to the row shape it handles and how it is called

    Tap a term, then the definition that fits it.

    Sources123

    3.Handler languages: in-line or staged, sharable or not

    Each handler language comes with two practical limits: where its code can live, and whether the resulting UDF can be shared. An in-line handler sits in the body of CREATE FUNCTION, between the $$ delimiters. A staged handler is code that has been packaged and uploaded to a stage, and the function definition points to it. Not every language supports staging. A sharable UDF can be used with Secure Data Sharing, which is covered in data sharing.

    Handler languages compared by where the code lives, whether the UDF is sharable, and which variations SQL can create
    LanguageHandler locationSharableVariations via CREATE FUNCTION
    SQLIn-lineYesUDF, UDTF
    JavaScriptIn-lineYesUDF, UDTF
    PythonIn-line or stagedNoUDF, UDAF, UDTF, Vectorized UDF, Vectorized UDTF
    JavaIn-line or stagedNoUDF, UDTF
    ScalaIn-line or stagedNoUDF

    The table explains the main trade-off. SQL and JavaScript keep everything in the function body and give you a function you can share. Python, Java and Scala can load code that has been built, packaged and uploaded separately, but the resulting function can't be shared. Each language also has its own type mappings between its native types and the SQL types used for arguments and return values. For example, a Snowpark Java UDF receives a SQL VARCHAR as a String.

    Checkpoint 4 of 11· Check yourself

    A data provider wants to offer consumer accounts a UDF through Secure Data Sharing. The UDF applies a string-cleanup rule. Which way of building it gives a function they can share?

    Sources1

    4.SQL and JavaScript handlers

    A SQL handler is a SQL expression, and the UDF returns whatever that expression evaluates to. The function below has no class, no handler name and no runtime version. Its body is the arithmetic itself. This makes SQL the simplest choice for a single reusable formula. Defined as a table function, a SQL handler can return a set of rows instead of a single value.

    A scalar SQL UDF: the body is the expression the function returnssql
    CREATE FUNCTION area_of_circle(radius FLOAT)
      RETURNS FLOAT
      AS
      $$
        pi() * radius * radius
      $$
      ;

    A JavaScript handler is code that runs in-line in the function body. For each row, it returns either one value or, if declared as a table function, a set of rows. Snowflake converts arguments and return values between SQL and JavaScript types. One detail catches people out: the JavaScript code must refer to input parameters in uppercase, even if they are declared in lowercase in the SQL signature. A handler that reads radius instead of RADIUS won't find the argument.

    JavaScript handlers are in-line only. The code lives in the function body and can't be loaded from a stage. That is why older projects that used JavaScript for string parsing move to Python once they need tested modules or third-party libraries. JavaScript's advantage over Python, Java and Scala is that the UDF stays sharable.

    Checkpoint 5 of 11· Check yourself

    A provider shares a JavaScript UDF that parses product codes with consumer accounts. The parsing now needs a tested module and a third-party library, kept as packaged code on a stage. What does moving to a staged handler involve?

    Sources45

    5.Python, Java and Scala handlers: packages and staged code

    Python handlers can use third-party libraries. Snowflake offers a curated list of Anaconda packages, and you name the ones you need in the PACKAGES clause of CREATE FUNCTION. Running SELECT * FROM INFORMATION_SCHEMA.PACKAGES WHERE LANGUAGE = 'python'; shows what is available. When a query calls the UDF, the packages are installed and cached on the warehouse for you. Only the handler changes: the function's name and SQL signature stay the same, so existing SQL callers keep calling it exactly as before.

    A Python UDTF: RETURNS TABLE makes it a table function, PACKAGES pulls in NumPy, HANDLER names the classsql
    CREATE OR REPLACE FUNCTION stock_sale_average(symbol VARCHAR, quantity NUMBER, price NUMBER(10,2))
      RETURNS TABLE (symbol VARCHAR, total NUMBER(10,2))
      LANGUAGE PYTHON
      RUNTIME_VERSION = 3.12
      PACKAGES = ('numpy')
      HANDLER = 'StockSaleAverage'
    AS $$
    import numpy as np
    
    class StockSaleAverage:
        def __init__(self):
          self._price_array = []
          self._quantity_total = 0
          self._symbol = ""
    
        def process(self, symbol, quantity, price):
          self._symbol = symbol

    Java and Scala handlers usually arrive as compiled code. You build the handler and its dependencies into a JAR, upload it to a stage, and point CREATE FUNCTION at it with the IMPORTS clause. The HANDLER clause then has to give the method name together with the class that contains it, in the form Class.method. An in-line handler can sometimes use the function name alone, but a staged one can't. With this setup, an existing compiled scoring model can run from SQL unchanged, without rewriting its logic in another language.

    Pin package versions in anything going to production. If you leave the version out, Snowflake resolves the latest one. A permanent UDF resolves its dependencies once, when it is created, and keeps using those versions. A temporary UDF resolves them again each time it is registered, so pin the version in its spec.

    Checkpoint 6 of 11· Match them up

    A team is writing CREATE FUNCTION statements for a Python UDTF that needs NumPy and a Java UDF that runs a compiled scoring model from a staged JAR. Pair each clause with the job it does in these definitions.

    Tap a term, then the definition that fits it.

    Checkpoint 7 of 11· Exam question

    A team is migrating logic from an older Snowflake project that used JavaScript UDFs for string parsing and now wants to add unit-testable, module-based Python code with third-party libraries such as regex, while keeping the function callable from plain SQL. Which change best meets the new requirement?

    Checkpoint 8 of 11· Exam question

    An engineering team already has a scoring model packaged as a compiled JAR that exposes a MyScorer.score(String) method, and they need to invoke that exact compiled artifact from Snowflake SQL without rewriting the model logic in another language. Which UDF definition matches this need?

    Sources367

    6.Registering UDFs and UDAFs with the Snowpark API

    With the Snowpark API, you write a UDF in client-side Python, Java or Scala, and the library handles deployment. It serializes your function, uploads it to a stage, and runs it on the server next to the data, so rows never travel to your laptop. Using these UDFs inside DataFrame pipelines is covered in Snowpark transformations. This section covers creating them.

    Snowpark registration involves two separate choices. Anonymous or named: an anonymous UDF is assigned to a variable and works only while that variable is in scope. A named UDF can be called by name, including from SQL. Temporary or permanent: register and udf create a temporary UDF by default, and it only lasts for the current session. Setting is_permanent=True creates a permanent UDF, and you must then supply stage_location so Snowpark knows where to upload the code. In code that may run across several sessions, use register rather than udf, which avoids errors when Snowpark can't find a default session.

    A named, permanent Snowpark Python UDF, which SQL can then call as minus_onepython
    @udf(name="minus_one", is_permanent=True, stage_location="@my_stage", replace=True)
    def minus_one(x: int) -> int:
      return x-1

    Dependencies have to be declared. In Python, session.add_import() uploads local files, directories or staged zip files, and session.add_packages() adds Anaconda packages for the whole session. A packages= argument on a single UDF overrides the session-level list. In Java, session.addDependency() does the same for JAR files and resource files. A JAR that is already on a stage doesn't need to be uploaded again on every run.

    A Python UDAF handler is a class whose methods Snowflake calls while it runs the aggregate. The same class works whether you register it with Snowpark (udaf, register or register_from_file) or create the UDAF with SQL. Snowflake splits the work across many partial states and then merges them, which is why a separate merge method is required.

    Methods a Python UDAF handler class must implement
    MethodWhat Snowflake uses it for
    __init__Initializes the internal state of the aggregate
    aggregate_stateReturns the internal state; needs the @property decorator and must be serializable by pickle
    accumulateUpdates the state from each new input row
    mergeCombines two intermediate aggregated states
    finishProduces the final result from the aggregated state

    Checkpoint 9 of 11· Fill the gap

    By default this decorator would create a UDF that disappears when the session ends. Which argument name in the blank makes minus_one last across sessions, so SQL can still call it later?

    @udf(name="minus_one",  ? =True, stage_location="@my_stage", replace=True)
    def minus_one(x: int) -> int:
      return x-1

    Sources862

    7.What the SECURE keyword hides

    You can declare a UDF SECURE when you create or alter it. Unauthorized users then can't see how the function works. In this context, "authorized" means holding a role that owns the function. Everyone else can still call it if they have been granted usage, but they can't see its internals in SHOW FUNCTIONS, SHOW USER FUNCTIONS, DESCRIBE FUNCTION, the FUNCTIONS Information Schema view, the Query Profile or GET_DDL. Error messages from secure functions may also be redacted.

    How a secure function's definition looks to a user without the owning role
    Hidden from unauthorized usersStill visible to them
    Body (the handler code)Parameter types
    List of importsReturn type
    Handler nameHandler language
    Packages listNull handling and volatility

    SECURE does not protect the stage. A Java, Python or Scala function hides its imports list, but the files those imports point to stay exactly as visible and accessible as the stage's own privileges allow. Anyone who can list that stage can still download the JAR. For these three languages, SECURE adds one more protection: each secure function runs in its own sandbox and shares no resources with other functions.

    Checkpoint 10 of 11· Check yourself

    The owner of a Java UDF declares it SECURE. Its IMPORTS clause points to a scoring JAR on the stage @models. An analyst has been granted usage on the function and privileges to list and read @models, but doesn't hold the owning role. What can the analyst do?

    Sources9

    8.Secure UDFs, the optimizer and indirect leaks

    Hiding the definition is only half of what a secure UDF does. The other half is how the optimizer treats it. Optimizations such as filter pushdown can reorder filters, and a general filter might then run before the filter that protects the data. A user could use that ordering to infer rows they aren't allowed to see. For a secure UDF, the optimizer skips those optimizations, which closes the leak. Skipping them can also make queries slower.

    Use SECURE for a specific purpose. Make a UDF secure when it exists to limit access to sensitive data. Leave a convenience function, for example one that hides an awkward data layout, as a regular UDF, because SECURE would slow it down for no gain. Apply the same standard to every access path: if only secure UDFs may read a table, any views over that table should probably be secure too.

    Even a secure function can leak through the values it returns. If it exposes an ID column filled from a sequence, a user who sees IDs 315 and 1455 can infer that roughly 1,139 rows were created in between, including rows they can't see. The fix is to leave such keys out, replace them with random identifiers from UUID_STRING, or obfuscate them. Snowflake also hides bytes and micro-partitions scanned for queries that use secure functions. Run times can still hint at data volume, though. When even that is too revealing, materialize a separate table for each role instead of exposing one function over the base data.

    Sharing changes which context functions are useful. In a secure UDF shared with another account, CURRENT_ROLE and CURRENT_USER return NULL, because the provider doesn't control the consumer's roles or users. Use CURRENT_ACCOUNT to authorize rows per consumer account. If a UDF, secure or not, is used inside a masking policy, its data type must match the data types of the column and the policy.

    Checkpoint 11 of 11· Check yourself

    Two new UDFs are up for review. The first returns only the rows of a salary table that the caller is allowed to see. The second flattens an awkward nested address layout, so analysts don't have to understand how the addresses are stored. Which plan follows Snowflake's guidance on the SECURE keyword?

    Sources9

    Practise it for real

    Create a Python scalar UDF, call it from SQL, then make it secure and compare what different roles can see.

    1. 1.Run CREATE OR REPLACE FUNCTION addone(i INT) RETURNS INT LANGUAGE PYTHON RUNTIME_VERSION = '3.12' HANDLER = 'addone_py' with an in-line body that defines addone_py(i) returning i+1.

      Why: This shows the parts every UDF has: a SQL signature, a handler language and a named handler.

      You should see: Snowflake reports that function ADDONE was created.

    2. 2.Run SELECT addone(3);

      Why: A UDF is called the same way as a built-in function, whatever its handler language.

      You should see: A single row with the value 4.

    3. 3.Recreate the function with the SECURE keyword, then run DESCRIBE FUNCTION addone(INT) as the owning role and again as a role that has only usage on it.

      Why: SECURE hides the body and handler name from roles that don't own the function, but leaves the signature visible.

      You should see: The owner sees the handler code. The other role sees the parameter types, return type and language, but not the body.

    Stuck? Get a nudge

    If the second role can't see the function at all, grant it usage on the database, schema and function before you compare the two outputs.

    Sources

    (9)

    Every claim above is drawn from one of these pages, quoted as it was written on the date shown.

    1. 1.
      “UDFs you create can be called in a way similar to built-in functions.”
      ↩︎ What a user-defined function is for
      “A function always returns a value explicitly by specifying an expression, so it’s a good choice for calculating and return a value.”
      ↩︎ What a user-defined function is for
      “Also known as a scalar function, returns one output row for each input row.”
      ↩︎ Scalar UDFs, UDTFs and UDAFs
      “Returns a tabular value for each input row.”
      ↩︎ Scalar UDFs, UDTFs and UDAFs
      “Python:UDF, UDAF, UDTF, Vectorized UDF, Vectorized UDTF”
      ↩︎ Scalar UDFs, UDTFs and UDAFs
      “A sharable UDF can be used with the Snowflake Secure Data Sharing feature.”
      ↩︎ Handler languages: in-line or staged, sharable or not
      “the function returns the database or schema that contains the UDF, not the database or schema in use for the session.”
      ↩︎ Handler languages: in-line or staged, sharable or not
      “You write a UDF’s logic – its handler – in one of the supported languages.”
      ↩︎ Key concept
      “Not all languages support referring to the handler on a stage (the handler code must instead be in-line).”
      ↩︎ Exam trap 5
      “User-defined table function (UDTF) | Returns a tabular value for each input row.”
      ↩︎ Checkpoint
      “Not all languages support referring to the handler on a stage (the handler code must instead be in-line).”
      ↩︎ Prediction
      “JavaScript | In-line | Yes”
      ↩︎ Checkpoint
      “Python | In-line or staged | No [2]”
      ↩︎ Checkpoint
    2. 2.
      “A UDAF takes one or more rows as input and produces a single row of output.”
      ↩︎ Scalar UDFs, UDTFs and UDAFs
      “Combines two intermediate aggregated states.”
      ↩︎ Registering UDFs and UDAFs with the Snowpark API
    3. 3.
      “Even when a call to the UDTF doesn’t include a PARTITION BY clause, Snowflake partitions the data implicitly.”
      ↩︎ Scalar UDFs, UDTFs and UDAFs
      “To specify these packages as dependencies in the UDTF, use the PACKAGES clause in CREATE FUNCTION.”
      ↩︎ Python, Java and Scala handlers: packages and staged code
    4. 4.
      “A SQL UDF evaluates an arbitrary SQL expression and returns the results of the expression.”
      ↩︎ SQL and JavaScript handlers
    5. 5.
      “the JavaScript code must refer to the input parameter names as all uppercase”
      ↩︎ SQL and JavaScript handlers
      “the UDF returns either a scalar (i.e. single) value or, if defined as a table function, a set of rows.”
      ↩︎ SQL and JavaScript handlers
    6. 6.
      “Anaconda packages are installed seamlessly and cached on the virtual warehouse on your behalf.”
      ↩︎ Python, Java and Scala handlers: packages and staged code
      “If you don’t specify a package version, Snowflake uses the latest version when resolving dependencies.”
      ↩︎ Python, Java and Scala handlers: packages and staged code
      “Calling register or udf will create a temporary UDF that you can use in the current session.”
      ↩︎ Registering UDFs and UDAFs with the Snowpark API
      “you must also set the stage_location argument”
      ↩︎ Registering UDFs and UDAFs with the Snowpark API
    7. 7.
      “When you’re using a staged handler, you use the IMPORTS clause to reference the handler at another location, such as a stage.”
      ↩︎ Python, Java and Scala handlers: packages and staged code
      “If necessary, such as with a handler written in Java or Scala, compile and package the handler code for uploading to a stage.”
      ↩︎ Python, Java and Scala handlers: packages and staged code
      “you must qualify the function name with the name of its containing class or module.”
      ↩︎ Exam trap 4
    8. 8.
      “the Snowpark library serializes and uploads the code for your UDF to a stage.”
      ↩︎ Registering UDFs and UDAFs with the Snowpark API
    9. 9.
      “to users who are granted a role that owns the function.”
      ↩︎ What the SECURE keyword hides
      “making the functions and procedures secure ensures that they are executed in separate sandboxes, such that no resources are shared between them.”
      ↩︎ What the SECURE keyword hides
      “You should not make a UDF secure when it is defined for query convenience”
      ↩︎ Secure UDFs, the optimizer and indirect leaks
      “Use randomized identifiers (such as those generated by UUID_STRING) instead of sequence-generated values.”
      ↩︎ Secure UDFs, the optimizer and indirect leaks
      “Snowflake does not expose the amount of data scanned (either in terms of bytes or micro-partitions) or the total amount of data.”
      ↩︎ Secure UDFs, the optimizer and indirect leaks
      “the CURRENT_ACCOUNT function can be used to authorize users from a specific account to access rows in a base table.”
      ↩︎ Secure UDFs, the optimizer and indirect leaks
      “Unauthorized users will still be able to see information that includes its:”
      ↩︎ Exam trap 1
      “the Snowflake query optimizer, when evaluating secure UDFs, bypasses the optimizations used for regular UDFs.”
      ↩︎ Exam trap 2
      “Using the SECURE keyword does not have any effect on the visibility of or access to those stages.”
      ↩︎ Exam trap 3
      “functions and procedures whose handlers are written in Java, Python, or Scala allow the IMPORTS clause, which imports code or data files from Snowflake stages.”
      ↩︎ Checkpoint
      “Unauthorized users will still be able to see information that includes its:”
      ↩︎ Prediction
      “Using the SECURE keyword does not have any effect on the visibility of or access to those stages.”
      ↩︎ Checkpoint

    Spotted a mistake, or was something unclear? Tell us.