CertSafari
    Databricks Certified Associate Developer for Apache Spark· Lessons

    Domain 3 · Lesson 19/32

    Python UDFs in PySpark: create, register and invoke

    Create and invoke user-defined functions with or without stateful operators, including StateStores.

    10 min read
    3% of exam
    2 sources
    Published 21 Oct 2026
    Docs as of 17 Oct 2026

    What you will be able to do

    • Wrap a Python function with udf or the @udf decorator and apply it to a DataFrame column
    • Register a Python function with spark.udf.register so SQL queries can call it by name
    • Protect a UDF from null input without relying on predicate evaluation order
    • Explain why row-at-a-time Python UDFs are slow and when a pandas UDF is the better choice

    Key concept

    Row-at-a-time Python UDF — A Python UDF wraps an ordinary Python function so that Spark can apply it to a column. Spark calls the function once for each row, and this per-row call is the reason for both its flexibility and its cost.

    1.Creating a Python UDF and calling it from DataFrames and SQL

    A Python user-defined function (UDF) lets you apply custom Python logic, such as a normalising rule or a small parser, to a column when no built-in function does the job. A UDF can be called in two ways. The DataFrame API calls a UDF object. SQL calls a registered name. You create each one in a different way, and mixing them up is the most common mistake.

    For the DataFrame API, wrap the function with pyspark.sql.functions.udf and pass a return type. Then call the object you get back on a column. If you have a plain normalize_country(code) function, write norm_udf = udf(normalize_country, StringType()) and then df.withColumn("country", norm_udf(df.country)). The @udf decorator does the same wrapping when the function is defined, so the decorated name is already a UDF and you can pass it a column directly.

    Declaring a UDF with the decorator and invoking it in selectpython
    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")))

    For SQL, register the function under a name with spark.udf.register(name, function, returnType). SQL text can then call that name. Registering does not change the original Python object. If you call the plain function directly on a column inside withColumn, Spark does not run it once per row: Python runs it once, right away, with a Column object as the argument, so code.strip() fails. A temp view queried through spark.sql can also only use functions that were registered by name. A function that is only defined in the Python session is unknown to SQL.

    Registering a typed UDF and calling it from SQLpython
    from pyspark.sql.types import LongType
    def squared_typed(s):
      return s * s
    spark.udf.register("squaredWithPython", squared_typed, LongType())
    
    spark.range(1, 20).createOrReplaceTempView("test")
    
    %sql select id, squaredWithPython(id) as id_squared from test

    Leaving out the return type does not cause an error. The UDF quietly returns strings. Numeric results then arrive as text, and later arithmetic or comparisons work on strings instead of numbers. You can declare the type as a DataType object such as LongType() or as a DDL string such as "long" or "int". Both forms are accepted by udf, the decorator and spark.udf.register.

    Checkpoint 1 of 5· Fill the gap

    The function is registered so that the temp view can be queried in SQL. Which name goes in the blank of the SQL query?

    from pyspark.sql.types import LongType
    def squared_typed(s):
      return s * s
    spark.udf.register("squaredWithPython", squared_typed, LongType())
    
    spark.range(1, 20).createOrReplaceTempView("test")
    
    %sql select id,  ? (id) as id_squared from test

    Checkpoint 2 of 5· Exam question

    A data engineer at a logistics company has a plain Python function: def normalize_country(code: str) -> str: return code.strip().upper() They need to apply it to the country column of a batch DataFrame df using the DataFrame API's .withColumn(). Which code correctly registers and applies the function?

    Sources1

    2.Nulls and evaluation order in SQL predicates

    A Python UDF receives SQL NULL as Python None. A body such as len(s) or code.strip() then raises an error on the executor, and the task fails. The obvious guard is WHERE s IS NOT NULL AND my_udf(s) > 1, but it is not reliable. Spark SQL does not promise to evaluate the parts of a predicate from left to right, so the UDF can still be called on rows that the null check was supposed to filter out.

    Two patterns do hold. The first is to make the UDF null-safe itself, so it returns a sentinel value for None instead of failing. The second is to put the call inside an IF or CASE WHEN branch. Spark evaluates the branch only when its condition is true, so the UDF never sees a null.

    A null-safe UDF, and a null check placed in 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 3 of 5· Check yourself

    A nightly SQL job fails with a TypeError from a Python UDF strlen whose body is len(s). The query's filter is WHERE s IS NOT NULL AND strlen(s) > 1. Which change makes the query safe without editing the UDF?

    Sources1

    3.Why row-at-a-time UDFs are slow, and when a pandas UDF wins

    A standard Python UDF is slow because of how often Spark calls it. Spark's engine runs in the JVM, but the function runs in Python. Each row's values go to the Python process, the function is called once for that single value, and the result comes back. On a billion-row DataFrame that means a billion Python calls, each with its own serialization overhead.

    A pandas UDF (a function wrapped with pandas_udf that takes and returns pandas Series, covered in Pandas UDFs (pandas_udf)) changes how data travels between the JVM and Python. Spark uses Apache Arrow to send a whole batch of rows in columnar form. The function runs once per batch as a vectorised pandas operation, and Spark joins the batch results back together. Fewer calls and columnar transfer are the whole speed-up. The Python code is not compiled to JVM bytecode or rewritten as a Catalyst expression, and results are not cached across batches.

    Row-at-a-time udf compared with a Series-to-Series pandas_udf
    AspectPython udfpandas_udf
    Declared withudf(f, LongType()) or @udf("long")pandas_udf with Python type hints
    Function receivesOne value per callA pandas Series per batch
    Data transferRow at a timeApache Arrow batches
    Function callsOnce per rowOnce per batch, results concatenated

    Choose a pandas UDF when the logic can be written as a whole-column operation, such as a * b or .str.upper() on a Series, and the data is large enough for per-row overhead to dominate. Keep a plain udf when the logic works on one Python value at a time and does not translate to Series operations. A pandas UDF is not a drop-in wrapper either. Passing normalize_country unchanged to pandas_udf breaks, because the function would get a Series, and a Series has no .strip() method.

    Checkpoint 4 of 5· Check yourself

    A job calls a row-at-a-time Python UDF on a billion-row DataFrame, and a teammate's rewrite with a Series-to-Series pandas_udf runs much faster. What explains the speed-up?

    Checkpoint 5 of 5· Exam question

    What is the primary technical reason a pandas_udf runs faster than an equivalent standard Python udf when processing large DataFrames?

    Sources2

    Sources

    (2)

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

    1. 1.
      “Alternatively, you can declare the same UDF using annotation syntax:”
      ↩︎ Creating a Python UDF and calling it from DataFrames and SQL
      “You can optionally set the return type of your UDF. The default return type is StringType.”
      ↩︎ Creating a Python UDF and calling it from DataFrames and SQL
      “Use IF or CASE WHEN expressions to do the null check and invoke the UDF in a conditional branch”
      ↩︎ Nulls and evaluation order in SQL predicates
      “handle subexpression evaluation-order caveats in Spark SQL”
      ↩︎ Nulls and evaluation order in SQL predicates
      “You can optionally set the return type of your UDF. The default return type is StringType.”
      ↩︎ Exam trap 1
      “Use IF or CASE WHEN expressions to do the null check and invoke the UDF in a conditional branch”
      ↩︎ Exam trap 2
    2. 2.
      “uses Apache Arrow to transfer data and pandas to work with the data”
      ↩︎ Why row-at-a-time UDFs are slow, and when a pandas UDF wins
      “Spark runs a pandas UDF by splitting the data into batches of rows, calling the function for each batch, and then concatenating the results.”
      ↩︎ Why row-at-a-time UDFs are slow, and when a pandas UDF wins
      “pandas UDFs allow vectorized operations that can increase performance up to 100x compared to row-at-a-time Python UDFs.”
      ↩︎ Key concept
      “is a user-defined function that uses Apache Arrow to transfer data and pandas to work with the data. pandas UDFs allow vectorized operations”
      ↩︎ Checkpoint

    Continue to part 2 of 2

    Stateful streaming operators, the StateStore and transformWithState

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