when / otherwise
Many columns are rules: "if the amount is over 1000 it is large, over 500 medium, otherwise small". when and otherwise write those rules as a column, checked row by row. This lesson shows how, why the order of the rules matters, and what happens when no rule matches.
Step 1 · PySpark functions · Bronze · Clean and type, lesson 4 of 5
On this page
Show code in
Every code block on the page follows this.
Read first: select · filter / where (skip if you know them)
In plain words first
A teacher turning marks into grades reads the rules from the top: 90 or more is an A, 75 or more a B, otherwise a C. They stop at the first rule that fits, so 92 is an A and the B rule is never looked at.
F.when is one rule, chained .when calls add more, and .otherwise is the last line, "everything else". Without it, a row that fits no rule gets nullnull: A missing or unknown value. Any comparison with null gives null, so filters treat it as false. Learn more →.
What it does
It builds a conditional expression, evaluated row by row. Chain more .when() calls for more branches and finish with .otherwise().
Step by step
Input
| name | salary |
|---|---|
| Chitra | 95000 |
| Asha | 72000 |
| Ben | 48000 |
| Farid | 39000 |
Output
| name | band |
|---|---|
| Chitra | senior |
| Asha | mid |
| Ben | junior |
| Farid | junior |
- 1For Chitra,
salary >= 90000is true: she getsseniorand the remaining branches are not checked. - 2For Asha, the first branch is false and the second,
salary >= 60000, is true:mid. - 3Ben and Farid match no branch, so they get the
otherwisevalue.
Run the example
Input: employees
| id | name | dept | salary | manager_id |
|---|---|---|---|---|
| 1 | Asha | Engineering | 72000 | null |
| 2 | Ben | Sales | 48000 | 1 |
| 3 | Chitra | Engineering | 95000 | 1 |
| 4 | Dev | HR | 51000 | 1 |
| 5 | Esha | Sales | 50000 | 2 |
| 6 | Farid | null | 39000 | 2 |
from pyspark.sql import functions as F result = employees.select( "name", F.when(F.col("salary") >= 90000, "senior") .when(F.col("salary") >= 60000, "mid") .otherwise("junior").alias("band"), )
SELECT name, CASE WHEN salary >= 90000 THEN 'senior' WHEN salary >= 60000 THEN 'mid' ELSE 'junior' END AS band FROM employees
Order matters
Branches are tested top to bottom. Put the most specific condition first: if salary >= 60000 came first, nobody would ever be senior, because 95,000 also passes that test.
Nulls and the missing otherwise
- Without
otherwise, unmatched rows get null. That is often a silent bug. - A condition that evaluates to null counts as false.
F.col("dept") == "HR"is null for Farid, so he falls through to the next branch. - All branch values must have a compatible type. Mixing a string and a number makes Spark cast or, in ANSI mode, fail.
Conditional aggregation
Putting when inside an aggregateaggregate: A function that turns many rows into one value per group: count, sum, avg, min, max. Learn more → counts or sums only some rows. It is the hand-written version of a pivotpivot: Turn the values of one column into column headings, with an aggregate in each cell. Learn more →, and works in a single pass.
Input: employees
| id | name | dept | salary | manager_id |
|---|---|---|---|---|
| 1 | Asha | Engineering | 72000 | null |
| 2 | Ben | Sales | 48000 | 1 |
| 3 | Chitra | Engineering | 95000 | 1 |
| 4 | Dev | HR | 51000 | 1 |
| 5 | Esha | Sales | 50000 | 2 |
| 6 | Farid | null | 39000 | 2 |
from pyspark.sql import functions as F result = employees.agg( F.count(F.when(F.col("salary") >= 60000, 1)).alias("high_earners"), F.sum( F.when(F.col("dept") == "Sales", F.col("salary")).otherwise(0) ).alias("sales_payroll"), )
SELECT COUNT(CASE WHEN salary >= 60000 THEN 1 END) AS high_earners, SUM(CASE WHEN dept = 'Sales' THEN salary ELSE 0 END) AS sales_payroll FROM employees
count skips nulls, and a when without otherwise is null for non-matching rows, so count(when(cond, 1)) counts exactly the matching rows.
Common mistakes
- Writing branches from general to specific — The general branch catches everything. Order from most to least specific.
- Forgetting otherwise — Unmatched rows become null and later aggregates silently skip them.
- Using Python if on a column —
if F.col("x") > 1:raises "Cannot convert column into bool". Conditions on columns must bewhen.
Key takeaways
whenchains are evaluated top to bottom; the first true branch wins.- No
otherwisemeans null for unmatched rows. - Null conditions count as false.
count(when(cond, 1))andsum(when(...))give conditional aggregates in one pass.
Interview prep
THE QUESTION
"Count, per department, how many people earn above and below 50,000, in one query."
F.count(F.when(F.col("salary") > 50000, 1)) and the opposite. Explain why it works: count ignores the nulls produced for non-matching rows. One pass, no join, no pivot.Avoid: filtering twice and joining the two results. One pass with conditional aggregates is the expected answer.
Follow-ups · answer out loud, then open
Follow-up"What does when() return for rows that match no condition and there is no otherwise()?"
count(when(cond, 1)) work, and also what produces surprise nulls in derived columns when a case was forgotten.Scenario"Map 40 country codes to regions. Would you write 40 when() clauses?"
F.create_map and look up the code. Both are easier to maintain, and the mapping can live in a reference table.Trap"In when(a > 10, 'high').when(a > 5, 'mid'), a value of 12 is labeled mid, because the last match wins."
Check yourself
3 questionsWhat does F.when(F.col("x") > 10, "big") return for x = 3?
Show the answer
null. With no otherwise, rows that match no branch get null.
Branches are when(x > 0, "pos").when(x > 100, "huge"). What is x = 500 labelled?
Show the answer
pos. The first true branch wins, and x > 0 is checked first. Reorder so the specific branch comes first.
Why does F.count(F.when(cond, 1)) count only matching rows?
Show the answer
Non-matching rows produce null, and count skips nulls. when without otherwise yields null for non-matching rows, and count(col) ignores nulls.
Practise this
Problems that use when / otherwise, graded on hidden tests
- Categorize OrdersConditional Logic Easy
- Conditional AggregationAggregations Medium
- Split Train and Test With No User in BothData Prep for AI Medium
Keep going
Up next · Clean and type · lesson 5 of 5 · 4 min readfillna / dropna
Fill or drop missing values per column, and why fillna(0) leaves string columns alone.
Related lessons
pivotPySpark functions · 4 min read
coalescePySpark functions · 5 min read
filter / where
Previous: Parsing dates and timestamps
Primary sources: functions.when · CASE clause