The situation
Two regional teams each export their sales. An AI assistant wrote the job that combines the two exports and reports net revenue per product. It runs without errors and the order counts match what the teams expect.
The net revenue does not. Some products look far less profitable than they are, and two products have negative revenue.
The AI-written code is in the answer cell. Find the bug and fix it.
Input tables
sales_north
One row per order from the north region.
| Column | Type | Description |
|---|---|---|
order_id |
BIGINT | Unique across both regions. |
product |
STRING | Product name. |
gross_amount |
DECIMAL(10,2) | Order value before discount. |
discount_amount |
DECIMAL(10,2) | Discount given. NULL means no discount was recorded. |
sales_south
One row per order from the south region. Same columns as sales_north. Run
sales_south.printSchema() before you trust that.
Requirement
Return net revenue per product across both regions.
- The net amount of an order is
gross_amountminusdiscount_amount. A NULL discount counts as 0. ordersis the number of orders of the product in both regions together.net_revenueis the sum of the net amounts of those orders.- A product sold in only one region still appears.
Expected output
One row per product.
| Column | Type | Description |
|---|---|---|
product |
STRING | |
orders |
BIGINT | Number of orders. |
net_revenue |
DECIMAL(12,2) | Sum of gross minus discount. |
The AI-written code
from pyspark.sql import functions as F def solve(spark): """Net revenue per product across both regions.""" north = spark.table("sales_north") south = spark.table("sales_south") # Combine both regions into a single DataFrame all_sales = north.union(south) # Net amount per order, treating a missing discount as zero all_sales = all_sales.withColumn( "net_amount", F.col("gross_amount") - F.coalesce(F.col("discount_amount"), F.lit(0)), ) # Aggregate per product result = all_sales.groupBy("product").agg( F.count("*").alias("orders"), F.sum("net_amount").cast("decimal(12,2)").alias("net_revenue"), ) return result
Explanation
Show explanationGives the answer away. Try the problem first.
The bug
all_sales = north.union(south)
DataFrame.union matches columns by position. It ignores column names completely
and keeps the names of the first DataFrame. The two tables have the same four columns
in a different order:
sales_north: order_id, product, gross_amount, discount_amount
sales_south: order_id, product, discount_amount, gross_amount
So for every south row, the discount lands in gross_amount and the gross value lands
in discount_amount. Net revenue for those rows becomes discount minus gross.
Nothing stops it. Both columns are DECIMAL(10,2), so the types line up and Spark has
no reason to complain. If one had been a string, the job would have failed and
somebody would have looked.
What the output looks like:
ordersis right for every product. Row counts are not affected by which column a value sits in.- "Standing Desk" is sold only in the north and is exactly right.
- "Footrest" is sold only in the south and comes out negative. "Webcam" is negative too, because its south rows outweigh its north rows.
- The other five products are a mix of right and wrong rows and merely look low.
The fix
all_sales = north.unionByName(south)
unionByName matches columns by name. If a name is missing on one side it fails
(unless you pass allowMissingColumns=True), which is what you want from a job that
combines files from different teams.
The alternative is to select the columns in the same order on both sides before a
plain union. That works, but it has to be repeated wherever the tables meet.
The same bug in SQL
UNION and UNION ALL in SQL are positional as well:
SELECT * FROM sales_north
UNION ALL
SELECT * FROM sales_south
This has exactly the same bug. In SQL, list the columns by name on both sides, in the
same order. Never SELECT * into a union.
Common wrong answers
Leaving union and fixing the arithmetic (taking the absolute value, or swapping
the subtraction for the south). It makes this output right and leaves a DataFrame in
which two columns mean different things depending on the row. The next person to use
all_sales inherits the bug.
Dropping the coalesce while fixing the union. A NULL discount makes
gross - discount NULL, and sum skips NULLs. Those orders then contribute nothing
to revenue, although they were sold at full price.
UNION instead of UNION ALL in SQL. UNION removes duplicate rows. It passes
here because order_id makes every row unique, but two identical rows in a table
without a key would be collapsed into one. Use UNION ALL unless you mean to
de-duplicate.
Edge cases in the data
| Case | Where | What it catches |
|---|---|---|
| Same columns, different order, same types | sales_south |
The bug itself. |
| Product sold only in the north | Standing Desk | Shows the bug touches only south rows. |
| Product sold only in the south | Footrest | Makes the swap obvious: negative revenue. |
| NULL discount | about 15% of orders | Losing full-price orders from the sum. |
| Discount of 0.00 | about 20% of orders | Treating 0 and NULL differently. |