Skip to content
Silver 4 min read · Nulls 2 practice problems ↓

coalesce

Missing values often have a sensible fallback: the shipping address, or else the billing address, or else "unknown". coalesce picks the first value that is not missing. This lesson shows how it works, how it differs from fillna, and the unrelated DataFrame method with the same name.

Step 1 · PySpark functions · Silver · Reshape and refine, lesson 1 of 7

Read first: select (skip if you know it)

In plain words first

Asking for a contact number, you try the mobile; if there is none, the office number; if there is none, the home number. You stop at the first one that exists.

F.coalesce(a, b, c) does that for every row: it returns the first argument that is not nullnull: A missing or unknown value. Any comparison with null gives null, so filters treat it as false. Learn more →, or null if all of them are.

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

Input: contacts

idwork_emailhome_emailphone
1a@work.coma@home.comnull
2nullb@home.com555-0102
3nullnull555-0103
4nullnullnull
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

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 joinleft join: A join that keeps every row of the left table, with nulls where the right side has no match. Learn more → leaves nulls where the right side had no match. coalesce turns them into a business default, for example zero orders:

PySparkSpark SQL
order_counts = orders.groupBy("customer_id").agg(F.count("*").alias("orders"))

customers.join(order_counts, "customer_id", "left") \
    .withColumn("orders", F.coalesce("orders", F.lit(0)))
WITH order_counts AS (
  SELECT customer_id, COUNT(*) AS orders FROM orders GROUP BY customer_id
)
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 DataFrameDataFrame: A table of rows and named columns that Spark processes in parallel. It never changes: every operation returns a new one. Learn more → method: merge partitionspartition: A chunk of a DataFrame's rows. Spark processes each partition as one task, so partitions decide how much work runs in parallel. Learn more → down to n without a full shuffleshuffle: Moving rows between machines so that all rows with the same key end up together. Needed by joins, groupBy and sorting, and usually the most expensive step of a job. Learn more →, 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.

Interview prep

THE QUESTION

"Build one customer address column from three sources with different priorities."

coalesce(crm_address, billing_address, shipping_address), in priority order. Mention that empty strings are not null, so wrap each in nullif(trim(x), '') first. That detail is what separates a good answer.

Avoid: treating empty strings as missing. coalesce skips only nulls, so an empty string in the first source wins.

Follow-ups · answer out loud, then open

Follow-up"How is F.coalesce different from fillna?"
F.coalesce picks the first non-null value among several columns or literals, row by row. fillna replaces nulls in columns with constants. Use coalesce to fall back to another column.
Scenario"Combine phone numbers from three systems, preferring the most recently updated non-null one."
Plain coalesce uses a fixed order. For "most recent", build structs of (updated_at, phone), drop null phones, and take F.max_by("phone", "updated_at") per customer, or sort an array of structs and take the first.
Trap"F.coalesce and DataFrame.coalesce do the same thing."
No. F.coalesce is a column function for nulls. df.coalesce(n) reduces the number of partitions. Same name, unrelated.

Check yourself

3 questions

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.

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").

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.

Practise this

Problems that use coalesce, graded on hidden tests

Keep going

Up next · Reshape and refine · lesson 2 of 7 · 4 min read
left_semi / left_anti
Keep the rows that have a match, or the rows that do not, without duplicating anything.

Related lessons

Previous: JSON and structs

Primary sources: functions.coalesce · DataFrame.fillna