Skip to main content
PYSPARK โ€ข LESSON 223

Latest Record Deduplication with row_number()

How can we keep only the most recent record for each natural key based on an updated_at timestamp?

Advancedโฑ 3 Minutesโญ 820 XP
๐Ÿค” THE QUESTION

How can we keep only the most recent record for each natural key based on an updated_at timestamp?

๐Ÿ’ก WHAT IS IT?

Partitioning by key and ordering by timestamp descending with row_number() assigns rank 1 to the newest event.

๐ŸŽฏ WHAT IS IT USED FOR?

Change Data Capture (CDC) pipelines where entities receive multiple state updates over time.

๐Ÿ’ป EXAMPLE
w = Window.partitionBy("customer_id").orderBy(col("updated_at").desc())
df_latest = df.withColumn("rn", row_number().over(w)).filter(col("rn") == 1).drop("rn")

๐ŸŽฏ Mission Objectives

Practice typing production-grade PySpark code for Latest Record Deduplication with row_number().

  • โœ“ Window partitioning by key
  • โœ“ Timestamp descending ordering
  • โœ“ Latest record selection with row_number == 1