The situation
Sales targets are set per region, and a region is a country plus a state. Small countries are managed as one region and have no state.
An AI assistant wrote the target report in the answer cell. It runs, returns one row per target, and the big regions look right. But the managers for Singapore and the UAE are being told they sold nothing this quarter, and they have the invoices to prove otherwise.
Find the bug and fix it.
Input tables
sales
One row per sale.
| Column | Type | Description |
|---|---|---|
sale_id |
BIGINT | Unique per sale. |
country |
STRING | Country code. Never NULL. |
state |
STRING | State code. NULL for countries that are managed as a single region. |
amount |
DECIMAL(10,2) | Sale value in rupees. |
targets
One row per region that has a target.
| Column | Type | Description |
|---|---|---|
country |
STRING | Country code. Never NULL. |
state |
STRING | State code. NULL for countries that are managed as a single region. |
target_amount |
DECIMAL(12,2) | The region's sales target for the quarter. |
Requirement
Return every region in targets with its actual sales.
- A sale belongs to a region if the country is the same and the state is the same. For a single-region country, the state is NULL on both sides and that counts as the same.
actual_amountis the sum of the region's sales, and 0.00 if it has none.achievedis true ifactual_amountis at leasttarget_amount.- Sales in regions without a target are ignored.
Expected output
One row per region in targets.
| Column | Type | Description |
|---|---|---|
country |
STRING | |
state |
STRING | NULL for single-region countries. |
target_amount |
DECIMAL(12,2) | |
actual_amount |
DECIMAL(14,2) | 0.00 if the region has no sales. |
achieved |
BOOLEAN |
The AI-written code
from pyspark.sql import functions as F def solve(spark): """Actual sales against target for every region.""" sales = spark.table("sales") targets = spark.table("targets") # Total sales per region actuals = sales.groupBy("country", "state").agg( F.sum("amount").alias("actual_amount") ) # Left join so that regions without any sales are kept report = targets.join(actuals, on=["country", "state"], how="left") # Regions without sales have an actual of zero report = report.withColumn( "actual_amount", F.coalesce(F.col("actual_amount"), F.lit(0)).cast("decimal(14,2)"), ) # Flag the regions that reached their target result = report.select( "country", "state", "target_amount", "actual_amount", (F.col("actual_amount") >= F.col("target_amount")).alias("achieved"), ) return result
Explanation
Show explanationGives the answer away. Try the problem first.
The bug
report = targets.join(actuals, on=["country", "state"], how="left")
Joining on a list of column names means targets.country = actuals.country AND
targets.state = actuals.state. For Singapore, state is NULL on both sides, and in
SQL NULL = NULL is not true. It is NULL, which a join treats as "no match".
So the Singapore target finds no sales. The left join keeps the target row, the
coalesce turns the missing actual into 0, and the report says Singapore sold
nothing. In fact it sold 8,22,342.00 against a target of 5,00,000.00.
Everything after the join made it worse, not better: the left join and the coalesce
were added to handle regions that really have no sales, and they make a failed match
look exactly like one.
Of the 13 target rows, 5 have a NULL state. Four of those have sales and are wrong; 62 of the 242 sales rows belong to them. Two regions flip from "achieved" to "not achieved".
Why it is hard to spot:
- The row count is right: one row per target.
- All eight regions with a state are correct.
- A region showing 0.00 is a normal thing for this report to contain. Two regions (Gujarat and Qatar) really did sell nothing.
The fix
Use a null-safe comparison for the column that can be NULL:
same_region = (targets["country"] == actuals["country"]) & targets["state"].eqNullSafe(actuals["state"])
report = targets.join(actuals, same_region, "left")
eqNullSafe treats two NULLs as equal and a NULL and a value as different. In SQL the
operator is <=>, and standard SQL spells it IS NOT DISTINCT FROM.
Because the join condition is now an expression rather than a list of names, both
country and state columns are in the result. Select the ones from targets
explicitly.
Common wrong answers
Replacing NULL with a placeholder on both sides, such as
coalesce(state, ''). This passes here. It works as long as the placeholder can never
be a real value, and it has to be applied identically everywhere the key is used. An
empty string that later turns up as real data, or one side using '' and the other
'N/A', brings the bug back. eqNullSafe says what is meant without inventing a
value.
Joining on country only. Returns 37 rows. Every Indian state's target is matched
with the sales of every Indian state.
Switching to an inner join with the null-safe condition. Returns 11 rows. The two regions with a target and no sales disappear. The left join was right; only the condition was wrong.
Removing the coalesce. The regions without sales show NULL instead of 0.00, and
achieved becomes NULL for them, since NULL >= target is NULL.
Where this comes up
Any composite key with an optional part: country and state, product and variant,
account and sub-account. It also appears when comparing two versions of a table to
find changed rows: old.city <> new.city misses every change to or from NULL, which
is the same rule seen from the other side (problem 4).
A useful habit: before joining on a column, check whether it can be NULL.
df.filter(F.col("state").isNull()).count() takes a few seconds and answers it.
Edge cases in the data
| Case | Regions | What it catches |
|---|---|---|
| NULL state on both sides, with sales | SG, AE, NP, LK | The bug itself. |
| NULL state, target but no sales | QA | Must be 0.00 for the right reason. |
| State present, target but no sales | IN-GJ | Inner join drops it. |
| Sales in a region without a target | US-WA, BD | Must not appear in the result. |
| Several states in one country | IN, US | Joining on country alone. |