28. Joining on Nullable Keys
Difficulty: Medium · Topics: Joins, Null Handling, Filtering & Selection
targets and actuals are keyed by (country, city). Country-level rows have city = null, and those should match each other too.
Inner-join the two so that null matches null. Return country, city, target, actual.
Row order does not matter; column names must match. Your code is graded on 3 test cases, including hidden edge cases.
Sample data
targets
| country | city | target |
|---|---|---|
| IN | null | 1000 |
| IN | Pune | 300 |
| US | NYC | 500 |
actuals
| country | city | actual |
|---|---|---|
| IN | null | 950 |
| IN | Pune | 320 |
| US | LA | 100 |
Expected output
| country | city | target | actual |
|---|---|---|---|
| IN | null | 1000 | 950 |
| IN | Pune | 300 | 320 |
Hints
Hint 1
A normal== never matches nulls: null == null is null, not true.Hint 2
Use the null-safe equalityeqNullSafe (SQL <=>) for each key.Hint 3
Alias the tables so you can pick one copy of each key column.Learn the concepts
- eqNullSafe (<=>) · 4 min read. Equality where null matches null: the fix for joins and comparisons that silently drop null keys.
- join · 5 min read. Combine DataFrames on a key: inner, left, right and full joins, and the duplicate-key fan-out trap.
- select · 6 min read. Choose, rename and compute columns, and why select beats a chain of withColumn calls.
PySpark functions you'll practise
- join
- eqNullSafe
- select
Related problems
- Customers Without Orders · Medium · Joins, Filtering & Selection
- Employees and Their Departments · Medium · Joins, Filtering & Selection
- Year-over-Year Growth · Medium · Joins, Filtering & Selection
- Employees Earning More than Their Manager · Medium · Joins, Filtering & Selection
- Order Lines with Product Details · Easy · Joins, Filtering & Selection
Browse
Topics: Window Functions · Joins · Aggregations · Pivot, Unpivot & Rollup · Arrays · Null Handling · Conditional Logic · Dates · Filtering & Selection · Strings · Data Lake · Lakehouse · Streaming · Data Prep for AI · Spark Performance
Difficulty: Easy · Medium · Hard · Learn · All problems · dbt practice