Skip to content
Good engineers know 3 min read · Nulls 2 practice problems ↓

coalesce

Take the first non-null value from several columns, and why it is not the same as fillna.

You will learn

  • How coalesce picks the first non-null value
  • The difference between coalesce, fillna and nvl
  • How to give a default to a missing join match
  • Why F.coalesce and DataFrame.coalesce are unrelated

Read first

Comfortable with these? Read on.

TL;DR F.coalesce(a, b, c) returns the first argument that is not null, row by row. Use it for fallbacks and defaults. Not to be confused with df.coalesce(n), which reduces the number of partitions.

What it does

It evaluates its arguments left to right and returns the first non-null one. If all are null, the result is null. Arguments must have compatible types.

Step by step

Input

idwork_emailhome_email
1a@work.coma@home.com
2nullb@home.com
3nullnull

Output

idbest_email
1a@work.com
2b@home.com
3none

A literal as the last argument guarantees a non-null result.

Run the example

PySparkSpark SQL
from pyspark.sql import functions as F
result = contacts.select(
    "id",
    F.coalesce("work_email", "home_email", F.lit("none")).alias("best_email"),
    F.coalesce("work_email", "home_email", "phone").alias("any_contact"),
)
SELECT id,
       COALESCE(work_email, home_email, 'none')  AS best_email,
       COALESCE(work_email, home_email, phone)   AS any_contact
FROM contacts

Switch to PySpark to edit and run this example in your browser.

Note F.lit("none"): in PySpark a plain string argument means a column name, so a literal must be wrapped in lit.

coalesce and its relatives

FunctionDoesNotes
F.coalesce(a, b, ...)First non-null of any number of expressionsThe general tool.
nvl(a, b) / ifnull(a, b)coalesce with exactly two argumentsSQL functions, also F.ifnull since 3.5.
df.fillna(value, subset)Replace nulls in whole columns with a constantValues only, no fallback to another column. Type must match the column.
nullif(a, b)Null when a equals b, else aThe reverse: turn sentinel values like 0 or "" into null.

Defaults after a left join

A left join leaves nulls where the right side had no match. coalesce turns them into a business default, for example zero orders:

PySparkSpark SQL
customers.join(order_counts, "customer_id", "left") \
    .withColumn("orders", F.coalesce("orders", F.lit(0)))
SELECT c.*, COALESCE(o.orders, 0) AS orders
FROM customers c
LEFT JOIN order_counts o USING (customer_id)
Watch out: think before replacing null with 0. "No orders" and "unknown" are different facts. A null average becomes a misleading 0, and averages computed later change because avg skips nulls but not zeros.

F.coalesce vs df.coalesce

F.coalesce(cols...)

A column function: first non-null value per row.

df.coalesce(n)

A DataFrame method: merge partitions down to n without a full shuffle, often before writing fewer files.

They share a name and nothing else. The Small file problem lesson covers df.coalesce(n).

Common mistakes

Passing a string literal without lit

F.coalesce("email", "unknown") looks for a column called unknown and fails.

Mixing types

coalescing a number with a string forces a cast; in ANSI mode an invalid one fails. Keep the types aligned.

Replacing null with 0 by reflex

It changes averages and hides missing data.

Key takeaways

  • F.coalesce returns the first non-null argument per row.
  • Wrap literals in F.lit.
  • Use it to give unmatched left-join rows a default, but only when the default is true.
  • df.coalesce(n) is a different thing: it reduces partitions.

Check yourself

3 questions

1. What does coalesce(null, '', 'x') return?

Show the answer

An empty string. An empty string is not null, so it is the first non-null value. Use nullif to treat blanks as missing.

2. Why does F.coalesce("a", "n/a") fail in PySpark?

Show the answer

"n/a" is treated as a column name. Plain strings are column names in the DataFrame API; use F.lit("n/a").

3. What does df.coalesce(1) do?

Show the answer

Reduces the DataFrame to one partition. The DataFrame method reduces the partition count. It is unrelated to F.coalesce.

Practice it

Interview problems that use coalesce: write the PySpark, run it, and get graded on hidden tests.

Solve: How Much Does Each Query Read? →

Go deeper

Primary sources: functions.coalesce · DataFrame.fillna