Skip to content
Bronze 5 min read · Selection 3 practice problems ↓

dropDuplicates

Duplicates sneak into data from retries, double loads and joins. Spark can remove rows that are completely identical, or rows that share the same key. This lesson shows both, which row survives when only the key matches, and how to keep the latest row per key on purpose rather than by luck.

Step 1 · PySpark functions · Bronze · Combine and summarise, lesson 2 of 4

Read first: groupBy + agg (skip if you know it)

In plain words first

A guest list has some names written twice. If the two lines are identical, you cross one out. If they share a name but have different phone numbers, you have to decide which one to keep: the newest, probably. Crossing out "any one of them" might keep the old number.

distinct removes identical rows. dropDuplicates(["name"]) keeps one row per name, but not a row you chose; to keep the newest, rank the rows first, as this lesson shows.

What it does

CallRemovesSQL
distinct()Rows identical in every columnSELECT DISTINCT *
dropDuplicates()Same as distinctSELECT DISTINCT *
dropDuplicates(["user_id"])Rows with the same user_id, keeping one of themNo direct equivalent; see below

Run the example

Remove exact duplicates, then keep one row per user:

PySparkSpark SQL

Input: events

user_idemailupdated_at
1a@x.com2025-01-01
1a@new.com2025-03-01
2b@x.com2025-02-01
2b@x.com2025-02-01
3c@x.com2025-01-15
exact = events.distinct()            # identical rows only
result = exact.dropDuplicates(["user_id"])   # one row per user_id, any one of them
SELECT DISTINCT * FROM events;

-- one row per user_id has no direct SQL form: use ROW_NUMBER (below)

Step by step

events

user_idemailupdated_at
1a@x.com2025-01-01
1a@new.com2025-03-01
2b@x.com2025-02-01
2b@x.com2025-02-01

distinct()

user_idemailupdated_at
1a@x.com2025-01-01
1a@new.com2025-03-01
2b@x.com2025-02-01

Only the exact duplicate for user 2 is removed. User 1 still has two rows because the emails differ.

Which row survives?

dropDuplicates(["user_id"]) keeps the first row it meets for each key, and "first" depends on partitioning and tasktask: The work for one partition in one stage, run on one CPU core. Learn more → timing. On a different day, with different file sizes, it can keep a different row. It is fine for exact duplicates; it is wrong for "keep the latest".

Keep the latest row per key

Rank the rows of each key by time with a window, and keep rank 1:

PySparkSpark SQL

Input: events

user_idemailupdated_at
1a@x.com2025-01-01
1a@new.com2025-03-01
2b@x.com2025-02-01
2b@x.com2025-02-01
3c@x.com2025-01-15
from pyspark.sql import functions as F
from pyspark.sql.window import Window

w = Window.partitionBy("user_id").orderBy(F.col("updated_at").desc())
result = (events
    .withColumn("row_num", F.row_number().over(w))
    .filter(F.col("row_num") == 1)
    .drop("row_num"))
SELECT user_id, email, updated_at
FROM (
  SELECT *, ROW_NUMBER() OVER (
    PARTITION BY user_id ORDER BY updated_at DESC) AS row_num
  FROM events)
WHERE row_num = 1

Some engines, such as Databricks SQL and Snowflake, accept QUALIFY row_num = 1 to skip the subquery. The subquery form works everywhere, including open-source Spark SQL. If two rows share the latest timestamp, add a tiebreaker to the orderBy.

Under the hood Optional deep dive

Both distinct and dropDuplicates are aggregationsaggregate: A function that turns many rows into one value per group: count, sum, avg, min, max. Learn more →: Spark groups by the chosen columns and keeps one row, with the same partial aggregation before the shuffleshuffle: Moving rows between machines so that all rows with the same key end up together. Needed by joins, groupBy and sorting, and usually the most expensive step of a job. Learn more → as a groupBy. In the plan they appear as HashAggregate nodes around an Exchange.

In Structured Streaming Optional deep dive

On a stream, dropDuplicates has to remember every key it has seen, forever, unless you bound the state with a watermarkwatermark: In streaming, how late data may arrive. Spark uses it to know when old state can be dropped. Learn more →: withWatermark("event_time", "1 hour").dropDuplicates(["event_id", "event_time"]). Spark 3.5 added dropDuplicatesWithinWatermark, which deduplicates on the key alone within the watermark delay.

Common mistakes

  • Using dropDuplicates to keep the latest version — With two versions of a customer (03-01 and 03-05), dropDuplicates(["customer_id"]) can keep 03-01 today and 03-05 tomorrow. Use row_number over a window ordered by time, newest first, and keep 1.
  • Deduplicating on all columns when a load timestamp differs — Two copies of order 42 loaded at 09:00 and 09:05 both survive distinct(), because ingested_at differs. Deduplicate on the business key: dropDuplicates(["order_id"]).
  • Unbounded streaming deduplication — On a stream, dropDuplicates(["event_id"]) remembers every id; after a month the state holds a month of ids and the job runs out of memory. Add a watermark.

Key takeaways

  • distinct() and dropDuplicates() with no columns are the same: rows identical in every column.
  • When two rows can share the latest timestamp, add a tiebreaker to the window's orderBy.
  • Both are aggregations: a HashAggregate around an Exchange, with the same partial aggregation before the shuffle as a groupBy.
  • Databricks SQL and Snowflake accept QUALIFY row_num = 1; open-source Spark SQL needs the subquery.

Interview prep

THE QUESTION

"How do you deduplicate a CDC feed so each customer keeps its most recent record?"

Window by customer_id, order by the change timestamp (plus a sequence number as a tiebreaker), take row_number() == 1. Say explicitly why not dropDuplicates: which row it keeps is not deterministic. For a lakehouse target you would then MERGE the result into the table.

Avoid: "dropDuplicates(['customer_id'])". It keeps an arbitrary row per key, not the latest.

Follow-ups · answer out loud, then open

Follow-up"Which row does dropDuplicates(['id']) keep?"
Whichever row comes first in its partition after the shuffle, which is not deterministic across runs. Never rely on it when you care which row survives.
Scenario"Two CDC records for the same customer have the same timestamp. How do you choose?"
Add a deterministic tiebreaker: the source sequence number or log offset if there is one, then the operation type (a delete after an update), then a hash of the row. Order by all of them in the window so the result is reproducible.
Trap"distinct() and dropDuplicates() are the same."
With no arguments they are equivalent. dropDuplicates also accepts a subset of columns, and in streaming it keeps state per key (bounded with a watermark, or dropDuplicatesWithinWatermark).

Check yourself

3 questions

Which row does dropDuplicates(["id"]) keep for a duplicated id?

Show the answer

An arbitrary one, which can change between runs. It keeps whichever row Spark meets first, which depends on partitioning. Use a window for a defined choice.

A table has a column loaded_at set at ingestion. What does distinct() remove?

Show the answer

Probably nothing, since loaded_at differs between loads. distinct compares every column. A per-load timestamp makes re-loaded rows unique.

What does a streaming dropDuplicates need to avoid unbounded state?

Show the answer

A watermark. The watermark tells Spark when old keys can be forgotten.

Practise this

Problems that use dropDuplicates, graded on hidden tests

See all 5 problems →

Keep going

Up next · Combine and summarise · lesson 3 of 4 · 5 min read
join
Combine DataFrames on a key: inner, left, right and full joins, and the duplicate-key fan-out trap.

Related lessons

Previous: groupBy + agg

Primary sources: DataFrame.dropDuplicates · DataFrame.distinct