25. Employees and Their Departments
Difficulty: Medium · Topics: Joins, Filtering & Selection
Join employees with departments on dept_id.
Return name and dept_name for every employee. If an employee has no department (null dept_id or an id that doesn't exist), dept_name must be null.
Row order does not matter; column names must match. Your code is graded on 3 test cases, including hidden edge cases.
Sample data
employees
| emp_id | name | dept_id |
|---|---|---|
| 1 | Asha | 10 |
| 2 | Ben | 20 |
| 3 | Chitra | null |
| 4 | Dev | 30 |
departments
| dept_id | dept_name |
|---|---|
| 10 | Engineering |
| 20 | Sales |
Expected output
| name | dept_name |
|---|---|
| Asha | Engineering |
| Ben | Sales |
| Chitra | null |
| Dev | null |
Hints
Hint 1
An inner join would drop employees without a department.Hint 2
Usehow="left" so every employee row is kept.Hint 3
Joining on a column name (string) avoids ambiguous duplicatedept_id columns.Learn the concepts
- 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
- select
Related problems
- Customers Without Orders · Medium · Joins, Filtering & Selection
- Year-over-Year Growth · Medium · Joins, Filtering & Selection
- Employees Earning More than Their Manager · Medium · Joins, Filtering & Selection
- Joining on Nullable Keys · Medium · Joins, Null Handling, 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