Skip to content

35. Upsert: Merge New Records into a Table

Difficulty: Hard · Topics: Window Functions, Filtering & Selection

You keep a current table and receive a batch of incoming records with the same columns. Produce the merged table: for each id, keep the version with the latest updated_at. If both have the same updated_at, the incoming one wins.

Return id, name, updated_at: one row per id.

Row order does not matter; column names must match. Your code is graded on 3 test cases, including hidden edge cases.

Sample data

current

idnameupdated_at
1Ana2024-01-01
2Bo2024-01-05

incoming

idnameupdated_at
2Bob2024-02-01
3Cy2024-02-01

Expected output

idnameupdated_at
2Bob2024-02-01
3Cy2024-02-01
1Ana2024-01-01

Hints

Hint 1Stack both tables with unionByName, tagging each row with a priority (incoming = 1, current = 2).
Hint 2Rank versions per id: newest updated_at first, then priority.
Hint 3Keep row_number() == 1 and drop the helper columns.

PySpark functions you'll practise

Related problems

Browse

Topics: Window Functions · Joins · Aggregations · Pivot, Unpivot & Rollup · Arrays · Null Handling · Conditional Logic · Dates · Filtering & Selection · Strings

Difficulty: Easy · Medium · Hard · PySpark interview roadmap · All problems