Skip to content

69. Apply a CDC Batch (MERGE Semantics)

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

target is the current table (id, name, tier). changes is a batch of change events with id, op ('I' insert, 'U' update, 'D' delete), name, tier and an increasing sequence number seq. An id can change several times in one batch.

Apply the batch the way MERGE INTO would: for each id only its latest change counts; a delete removes the row, an insert or update writes the new values (an update for an unknown id is treated as an insert). Return the resulting table: id, name, tier.

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

Sample data

target

idnametier
1Ashafree
2Benpro
3Chitrafree

changes

idopnametierseq
2UBenenterprise1
3Dnullnull2
4IDevfree3
4UDevpro4

Expected output

idnametier
1Ashafree
2Benenterprise
4Devpro

Hints

Hint 1First reduce changes to the latest event per id: row_number over a window by id ordered by seq descending.
Hint 2Rows of target with no change at all are kept as they are: a left_anti join finds them.
Hint 3Union the untouched rows with the latest changes whose op is not 'D'.

Learn the concepts

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 · Learn · All problems