CertSafari
    Databricks Certified Data Engineer Professional - October 9 onwards· Lessons

    Domain 1 · Lesson 3/45

    Built-in functions, Python UDFs and pandas UDFs in Spark

    Develop User-Defined Functions (UDFs) using Pandas, Python, and SQL, including Unity Catalog functions for the given constraints.

    13 min read
    1.92% of exam
    4 sources
    Published 22 Oct 2026
    Docs as of 17 Oct 2026

    What you will be able to do

    • Choose between a built-in function, a SQL UDF, a row-at-a-time Python UDF and a pandas UDF, based on performance, how complex the logic is and whether it needs governance
    • Write null-safe Python UDFs that do not depend on SQL short-circuit evaluation
    • Pick the pandas UDF variant or pandas function API whose row-count and setup behaviour fits the job

    Key concept

    Built-in first, UDF for the gap — Spark's built-in functions are the optimized default. A user-defined function is justified only when built-ins cannot reasonably express the logic. Even then, the UDF type you pick decides how much per-row overhead you pay and who else can reuse the code.

    1.Choosing between built-in functions and UDFs

    A user-defined function (UDF) is custom code that Spark calls from inside a query. Every kind of UDF costs something that a built-in function does not. Spark's own functions are optimized for distributed processing and perform better at scale, so the first question for any transformation is whether built-ins can express it. A UDF is worth writing only for logic that built-ins handle badly, such as custom hashing, validation rules or an in-house parsing format.

    Databricks also decides by workload, not only by logic. UDFs suit ad hoc queries, manual data cleaning, exploratory analysis and small to medium datasets. Large datasets and anything that runs regularly or continuously, such as scheduled ETL jobs and streaming, belong on Spark methods. If custom code can't be avoided, two questions remain: how the code runs (one row at a time or in Arrow batches) and who can reuse it (one session, or everyone through Unity Catalog).

    Function options and when each one wins
    OptionHow it runsWins when
    Built-in Spark functionNative and optimized for distributed processingBuilt-ins can express the logic, especially for large datasets, scheduled ETL and streaming
    SQL UDF (e.g. RETURN LENGTH(name))A SQL expression body, registered under a nameThe logic is plain SQL but should be named, reused and governed as one function
    Python UDF (@udf)One Python call per rowCustom Python on small to medium data, ad hoc work, exploration
    pandas UDF (@pandas_udf)Arrow batches passed as pandas SeriesCustom Python on enough data that per-row overhead hurts
    Unity Catalog function (CREATE FUNCTION)Persisted in a catalog and schema, governed by permissionsTeams, notebooks, jobs and SQL warehouses need to share the same logic

    Checkpoint 1 of 6· Check yourself

    A nightly scheduled ETL job processes a multi-billion-row table. It needs to upper-case a customer name column and compute its length. A teammate suggests a custom Python function for this. What should you use?

    Sources1

    2.Row-at-a-time Python UDFs and null handling

    A scalar Python UDF calls a Python function once for each row and returns one value per row. It is session-scoped. You define it in a notebook or job with the udf decorator or by wrapping a function in udf(). spark.udf.register makes it callable by name from SQL in the same session. The return type is optional, but if you leave it out Spark assumes StringType. Declare it explicitly, as with "long" below, whenever the result is not a string.

    A session-scoped Python UDF declared with the decorator and an explicit return typepython
    from pyspark.sql.functions import udf
    
    @udf("long")
    def squared_udf(s):
      return s * s
    df = spark.table("test")
    display(df.select("id", squared_udf("id").alias("id_squared")))

    Evaluation order is where Python UDFs break most often. Spark SQL does not guarantee the order in which subexpressions run, and logical AND and OR do not short-circuit from left to right. The optimizer can also reorder WHERE and HAVING clauses. A filter that looks protective can therefore still pass NULL into the function, and len(None) fails the query. There are two safe patterns. You can make the UDF itself handle None, or you can call it only inside an IF or CASE WHEN branch that runs for non-null input.

    Both null-safe patterns: a null-aware UDF, and a UDF called only inside a conditional branchpython
    spark.udf.register("strlen_nullsafe", lambda s: len(s) if not s is None else -1, "int")
    spark.sql("select s from test1 where s is not null and strlen_nullsafe(s) > 1") # ok
    spark.sql("select s from test1 where if(s is not null, strlen(s), null) > 1")   # ok

    Checkpoint 2 of 6· Fill the gap

    The plain strlen UDF below is not null-aware. Which function in the last query makes sure Spark calls it only for non-null input?

    spark.udf.register("strlen_nullsafe", lambda s: len(s) if not s is None else -1, "int")
    spark.sql("select s from test1 where s is not null and strlen_nullsafe(s) > 1") # ok
    spark.sql("select s from test1 where  ? (s is not null, strlen(s), null) > 1")   # ok

    Sources2

    3.pandas UDFs: vectorized batches over Arrow

    A pandas UDF, also called a vectorized UDF, moves data to Python with Apache Arrow and gives your function pandas objects instead of single values. Vectorized operations on whole batches can run up to 100x faster than row-at-a-time Python UDFs. That makes a pandas UDF the right choice once custom Python logic meets real data volume. You declare one with pandas_udf and Python type hints, and the type hints decide which variant you get.

    The Series to Series variant is the vectorized form of a scalar UDF. Spark splits the data into batches of rows, calls the function once per batch and concatenates the results. The function must therefore return a Series of the same length as its input. Because it is an ordinary pandas function, you can test it on a local pd.Series before running it on a cluster.

    A Series to Series pandas UDF used with withColumnpython
    from pyspark.sql.functions import pandas_udf
    import pandas as pd
    
    df = spark.createDataFrame([(70, 1.75), (80, 1.80), (60, 1.65)], ["Weight", "Height"])
    
    @pandas_udf("double")
    def calculate_bmi_pandas(weight: pd.Series, height: pd.Series) -> pd.Series:
      return weight / (height ** 2)
    
    df.withColumn("BMI", calculate_bmi_pandas(df["Weight"], df["Height"])).display()

    Running once per batch becomes a problem when setup is expensive. Anything inside a Series to Series function, such as deserializing a model file or opening a client, runs again for every batch. The Iterator of Series to Iterator of Series variant solves this. The function receives an iterator of batches, so code placed before the loop runs once and the loop body scores each batch. The total output must still match the total input in length, which keeps exactly one result per input row. Wrap the setup in try/finally or a context manager so resources are released when the iterator ends.

    Iterator pandas UDF: initialize state before the loop, release it in finallypython
    # In the UDF, you can initialize some state before processing batches.
    # Wrap your code with try/finally or use context managers to ensure
    # the release of resources at the end.
    y = 1  # value captured by the UDF closure
    
    @pandas_udf("long")
    def plus_y(batch_iter: Iterator[pd.Series]) -> Iterator[pd.Series]:
        try:
            for x in batch_iter:
                yield x + y
        finally:
            pass  # release resources here, if any

    Neighbouring APIs look similar but break one of these guarantees. DataFrame.mapInPandas() also iterates over batches, but it can return output of any length, so it cannot promise one score per input row. Grouped applyInPandas() calls its function once per group, so setup placed inside that function runs for every group.

    pandas UDF variants by type hint and row-count rule
    VariantType hintRow-count ruleTypical use
    Series to Seriespd.Series -> pd.SeriesOutput length equals input batch lengthVectorized scalar logic in select or withColumn
    Iterator of Series to Iterator of SeriesIterator[pd.Series] -> Iterator[pd.Series]Total output length equals total input lengthExpensive one-time setup, e.g. loading a model
    Iterator of multiple Series to Iterator of SeriesIterator[Tuple[pd.Series, pd.Series]] -> Iterator[pd.Series]Same as the single-column iteratorSetup once, several input columns
    Series to scalarpd.Series -> intOne value per groupA UDAF with groupBy().agg(); session-scoped only

    Checkpoint 3 of 6· Check yourself

    You need to score every row of a large DataFrame with an ML model whose file takes several seconds to deserialize. Each input row must get exactly one score, and the model should be loaded as few times as possible. Which approach fits?

    Checkpoint 4 of 6· Exam question

    A data engineering team calls a Python UDF that scores millions of rows using a machine learning model loaded from a serialized file. Loading the model takes several seconds, and the current scalar pandas_udf reloads the model on every batch, causing high per-partition overhead. Which pandas UDF design lets the model load exactly once per Python worker process while still returning one score for every input row?

    Sources341

    4.Grouped pandas logic with applyInPandas

    Some logic doesn't work row by row. Per-group statistics and as-of joins need to see a whole slice of the data at once. The pandas function APIs handle this. They apply a native Python function to a PySpark DataFrame in pandas form, using the same Arrow-based execution as pandas UDFs. Unlike pandas UDFs, they are DataFrame methods rather than column expressions, and type hints are optional.

    groupBy().applyInPandas() follows a split-apply-combine pattern. You call groupBy first to split the data. Spark then passes your function one group at a time as a pandas DataFrame containing every row and every column of that group, grouping key included. The DataFrames your function returns are combined into a new PySpark DataFrame. Spark needs the output schema up front, as a StructType or a DDL string. The column labels of each returned DataFrame must match the schema's field names, or match its types by position if the labels aren't strings. The output is a whole DataFrame shaped by that schema, not a Series tied to the input, so the equal-length rule of Series to Series UDFs does not apply.

    Grouped map: subtract each group's mean, with the output schema declaredpython
    def subtract_mean(pdf):
        # pdf is a pandas.DataFrame
        v = pdf.v
        return pdf.assign(v=v - v.mean())
    
    df.groupby("id").applyInPandas(subtract_mean, schema="id long, v double").show()

    The main cost of applyInPandas is memory. Spark loads a whole group into memory before calling the function, and the maxRecordsPerBatch setting does not split groups. With skewed data, a single huge key can cause an out-of-memory failure, so group on a key whose largest group fits on a worker. A related API, groupby().cogroup().applyInPandas(), gives the function the matching groups from two DataFrames. It is useful for operations like an as-of join with pd.merge_asof, and it has the same memory constraint.

    Checkpoint 5 of 6· Check yourself

    Inside df.groupby("id").applyInPandas(f, schema="id long, v double"), the function f returns 1 summary row for a group that came in with 5,000 rows. How does Spark handle this?

    Checkpoint 6 of 6· Exam question

    A team runs sales_df.groupBy("region").applyInPandas(compute_stats, schema=result_schema) to execute a custom Python function that computes a variable number of summary rows per region using pandas operations that are not expressible in Spark SQL. Which two statements correctly describe how applyInPandas behaves in this scenario?(Select 2)

    0 of 2 selected

    Sources4

    Sources

    (4)

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

    1. 1.
      “Built-in Apache Spark functions are optimized for distributed processing and offer better performance at scale.”
      ↩︎ Choosing between built-in functions and UDFs
      “Databricks recommends UDFs for ad hoc queries, manual data cleaning, exploratory data analysis, and operations on small to medium-sized datasets.”
      ↩︎ Choosing between built-in functions and UDFs
      “Use Apache Spark methods for operations on large datasets and any workloads that run regularly or continuously, including ETL jobs and streaming operations.”
      ↩︎ Choosing between built-in functions and UDFs
      “UDAFs operate on multiple rows and return a single aggregated result. UDAFs are session-scoped only.”
      ↩︎ pandas UDFs: vectorized batches over Arrow
      “Use UDFs for logic that is difficult to express with built-in Apache Spark functions.”
      ↩︎ Key concept
      “Non-scalar UDFs operate on entire datasets/columns with flexible input/output ratios (1:N or many:many).”
      ↩︎ Checkpoint
    2. 2.
      “You can optionally set the return type of your UDF. The default return type is StringType.”
      ↩︎ Row-at-a-time Python UDFs and null handling
      “logical AND and OR expressions do not have left-to-right “short-circuiting” semantics”
      ↩︎ Row-at-a-time Python UDFs and null handling
      “there's no guarantee that the null check will happen before invoking the UDF”
      ↩︎ Exam trap 1
      “there's no guarantee that the null check will happen before invoking the UDF”
      ↩︎ Prediction
    3. 3.
      “pandas UDFs allow vectorized operations that can increase performance up to 100x compared to row-at-a-time Python UDFs.”
      ↩︎ pandas UDFs: vectorized batches over Arrow
      “The length of the entire output in the iterator should be the same as the length of the entire input.”
      ↩︎ pandas UDFs: vectorized batches over Arrow
      “useful when the UDF execution requires initializing some state, for example, loading a machine learning model file”
      ↩︎ pandas UDFs: vectorized batches over Arrow
      “Spark runs a pandas UDF by splitting the data into batches of rows, calling the function for each batch, and then concatenating the results.”
      ↩︎ Exam trap 2
      “useful when the UDF execution requires initializing some state, for example, loading a machine learning model file to apply inference to every input batch.”
      ↩︎ Checkpoint
    4. 4.
      “It can return output of arbitrary length in contrast to some pandas UDFs such as Series to Series.”
      ↩︎ pandas UDFs: vectorized batches over Arrow
      “Split the data into groups by using DataFrame.groupBy.”
      ↩︎ Grouped pandas logic with applyInPandas
      “A StructType object or a string that defines the schema of the output DataFrame”
      ↩︎ Grouped pandas logic with applyInPandas
      “The configuration for maxRecordsPerBatch is not applied on groups”
      ↩︎ Grouped pandas logic with applyInPandas
      “All data for a group is loaded into memory before the function is applied.”
      ↩︎ Exam trap 3
      “The input data contains all the rows and columns for each group.”
      ↩︎ Prediction

    Continue to part 2 of 2

    Unity Catalog functions: create, grant and call governed UDFs

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