Skip to content
Bronze 4 min read · Conditional 3 practice problems ↓

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

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

namesalary
Chitra95000
Asha72000
Ben48000
Farid39000

Output

nameband
Chitrasenior
Ashamid
Benjunior
Faridjunior
  1. 1
    For Chitra, salary >= 90000 is true: she gets senior and the remaining branches are not checked.
  2. 2
    For Asha, the first branch is false and the second, salary >= 60000, is true: mid.
  3. 3
    Ben and Farid match no branch, so they get the otherwise value.

Run the example

PySparkSpark SQL

Input: employees

idnamedeptsalarymanager_id
1AshaEngineering72000null
2BenSales480001
3ChitraEngineering950001
4DevHR510001
5EshaSales500002
6Faridnull390002
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.

PySparkSpark SQL

Input: employees

idnamedeptsalarymanager_id
1AshaEngineering72000null
2BenSales480001
3ChitraEngineering950001
4DevHR510001
5EshaSales500002
6Faridnull390002
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 be when.

Key takeaways

  • when chains are evaluated top to bottom; the first true branch wins.
  • No otherwise means null for unmatched rows.
  • Null conditions count as false.
  • count(when(cond, 1)) and sum(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."

Group by department and use two conditional aggregates: 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()?"
null. That is what makes 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?"
No. Put the mapping in a small DataFrame and join (Spark will broadcast it), or build a map literal with 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."
The first matching condition wins, like CASE WHEN. 12 is 'high'. Order conditions from most to least specific.

Check yourself

3 questions

What 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

See all 16 problems →

Keep going

Up next · Clean and type · lesson 5 of 5 · 4 min read
fillna / dropna
Fill or drop missing values per column, and why fillna(0) leaves string columns alone.

Related lessons

Previous: Parsing dates and timestamps

Primary sources: functions.when · CASE clause