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
On this page
Show code in
Every code block on the page follows this.
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
| id | work_email | home_email |
|---|---|---|
| 1 | a@work.com | a@home.com |
| 2 | null | b@home.com |
| 3 | null | null |
Output
| id | best_email |
|---|---|
| 1 | a@work.com |
| 2 | b@home.com |
| 3 | none |
A literal as the last argument guarantees a non-null result.
Run the example
Input: contacts
| id | work_email | home_email | phone |
|---|---|---|---|
| 1 | a@work.com | a@home.com | null |
| 2 | null | b@home.com | 555-0102 |
| 3 | null | null | 555-0103 |
| 4 | null | null | null |
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
| Function | Does | Notes |
|---|---|---|
F.coalesce(a, b, ...) | First non-null of any number of expressions | The general tool. |
nvl(a, b) / ifnull(a, b) | coalesce with exactly two arguments | SQL functions, also F.ifnull since 3.5. |
df.fillna(value, subset) | Replace nulls in whole columns with a constant | Values only, no fallback to another column. Type must match the column. |
nullif(a, b) | Null when a equals b, else a | The 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:
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)
F.coalesce vs df.coalesce
F.coalesce(cols...)
df.coalesce(n)
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.coalescereturns 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?"
Scenario"Combine phone numbers from three systems, preferring the most recently updated non-null one."
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."
F.coalesce is a column function for nulls. df.coalesce(n) reduces the number of partitions. Same name, unrelated.Check yourself
3 questionsWhat 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 readleft_semi / left_anti
Keep the rows that have a match, or the rows that do not, without duplicating anything.
Related lessons
when / otherwisePySpark functions · 4 min read
eqNullSafe (<=>)Spark internals · 8 min read
The small file problem
Previous: JSON and structs
Primary sources: functions.coalesce · DataFrame.fillna