Apache Spark logo for the PySpark remove duplicates guide
9
Views

Duplicate records are one of the most common problems in data engineering. A source system sends the same file twice, an API retries a call, or a CDC feed sends many versions of the same row. If you do not remove duplicates, your reports show wrong totals and your joins explode. That is why “How do you remove duplicates in PySpark?” is asked in almost every data engineering interview.

In this guide we will compare the three main ways to remove duplicates in PySpark and SQL: distinct(), dropDuplicates() and ROW_NUMBER(). Let’s break it down in simple words.

Apache Spark logo for the PySpark remove duplicates guide
Image credit: Apache Spark logo by the Spark project team, Apache License 2.0, via Wikimedia Commons.

Quick summary: remove duplicates in PySpark

  • distinct() removes rows that are 100% the same in every column.
  • dropDuplicates([“col”]) removes rows that are the same in selected columns, but it does not let you choose which row is kept.
  • ROW_NUMBER() with a window lets you keep exactly the row you want, for example the latest record.

Sample data to remove duplicates in PySpark

Imagine an orders table. Order 101 came three times: two rows are exact copies, and one row is an updated version with a new amount.

from pyspark.sql import SparkSession

spark = SparkSession.builder.appName("dedup-demo").getOrCreate()

data = [
    (101, "C1", 500, "2026-11-01 10:00:00"),
    (101, "C1", 500, "2026-11-01 10:00:00"),   # exact copy
    (101, "C1", 650, "2026-11-02 09:30:00"),   # updated version
    (102, "C2", 300, "2026-11-01 11:15:00"),
]
df = spark.createDataFrame(data, ["order_id", "customer_id", "amount", "updated_at"])
df.show()

Method 1: distinct() – remove exact duplicate rows

distinct() compares every column. A row is removed only if another row has the same value in all columns. Therefore, this is the simplest way to remove duplicates in PySpark.

df.distinct().show()
# Result: 3 rows
# (101, C1, 500, 2026-11-01 10:00:00)
# (101, C1, 650, 2026-11-02 09:30:00)
# (102, C2, 300, 2026-11-01 11:15:00)

The exact copy is gone, but order 101 still appears twice because the amounts are different. So distinct() is good for cleaning pure copies, not for “one row per key”. In SQL, the same thing is SELECT DISTINCT * FROM orders.

Method 2: dropDuplicates() – remove duplicates by key columns

dropDuplicates() takes an optional list of columns (called a subset). Spark keeps only one row for each unique combination of those columns. If you call it with no columns, it behaves like distinct(). It also has an alias, drop_duplicates(). For example, you can remove duplicates in PySpark by order_id alone.

df.dropDuplicates(["order_id"]).show()
# Result: 2 rows - one for 101 and one for 102
# But which 101 row is kept (500 or 650)? Not guaranteed!

This is the big interview trap. Spark works in parallel across many partitions, so dropDuplicates() does not promise to keep the first, last or latest row. Even sorting the DataFrame with orderBy() before it is not a safe guarantee. Use dropDuplicates() only when any one of the duplicate rows is fine for you.

Method 3: ROW_NUMBER() – keep exactly the row you want

In real projects you usually want “the latest record for each key”. For this, use a window function. We group rows by the key (partitionBy), sort inside each group (orderBy), give each row a number, and keep row number 1. As a result, you can remove duplicates in PySpark with full control.

from pyspark.sql import Window
from pyspark.sql import functions as F

w = Window.partitionBy("order_id").orderBy(F.to_timestamp("updated_at").desc())

latest_df = (
    df.withColumn("rn", F.row_number().over(w))
      .filter(F.col("rn") == 1)
      .drop("rn")
)
latest_df.show()
# Result: 2 rows
# (101, C1, 650, 2026-11-02 09:30:00)  -> latest version kept
# (102, C2, 300, 2026-11-01 11:15:00)

Now the result is predictable: you always get the newest row for each order. Tip: if two rows can have the same updated_at, add a second sort column (like an ingestion id) as a tie-breaker. Otherwise even row_number() may pick either row.

Remove duplicates in PySpark SQL: the same logic

This query works in Spark SQL, Snowflake, SQL Server, PostgreSQL and most modern databases: Similarly, you can remove duplicates in PySpark SQL with a window function.

SELECT order_id, customer_id, amount, updated_at
FROM (
    SELECT *,
           ROW_NUMBER() OVER (PARTITION BY order_id
                              ORDER BY updated_at DESC) AS rn
    FROM orders
) t
WHERE rn = 1;

Databricks SQL and Snowflake also support the QUALIFY clause, which filters on a window function directly, so you do not need a subquery:

SELECT *
FROM orders
QUALIFY ROW_NUMBER() OVER (PARTITION BY order_id
                           ORDER BY updated_at DESC) = 1;

Interviewers also like asking, “How do you first find the duplicates?” A simple GROUP BY with HAVING does the job:

SELECT order_id, COUNT(*) AS cnt
FROM orders
GROUP BY order_id
HAVING COUNT(*) > 1;

ROW_NUMBER vs RANK vs DENSE_RANK for deduplication

  • ROW_NUMBER() always gives 1, 2, 3… with no repeats. Filtering rn = 1 returns exactly one row per key. Best for dedup.
  • RANK() gives the same rank to ties (1, 1, 3). Filtering rank 1 can return more than one row per key.
  • DENSE_RANK() also repeats ranks for ties (1, 1, 2), so it has the same problem for dedup.

Bonus: removing duplicates in Structured Streaming

In a streaming job, dropDuplicates() has to remember every key it has seen, so its state can keep growing. You can limit this with a watermark. From Spark 3.5, there is also dropDuplicatesWithinWatermark(), which removes duplicates that arrive within the watermark delay even if their event times are slightly different.

deduped_stream = (
    events_stream
        .withWatermark("event_time", "10 minutes")
        .dropDuplicatesWithinWatermark(["event_id"])
)

Which method should you use to remove duplicates in PySpark?

  • Rows are exact copies (same file loaded twice) → distinct().
  • One row per key and any row is fine → dropDuplicates(["key"]).
  • One row per key and you must keep the latest/highest/first → ROW_NUMBER() window.
  • Streaming data → watermark plus dropDuplicatesWithinWatermark() or dropDuplicates().

Performance note: all three methods cause a shuffle, because Spark must bring rows with the same key to the same place. On very large tables, deduplicate early, select only the columns you need, and remove duplicates before big joins.

Key takeaways on how to remove duplicates in PySpark

  • distinct() = remove rows identical in all columns.
  • dropDuplicates(subset) = one row per key, but the kept row is not guaranteed.
  • ROW_NUMBER() + filter rn = 1 = deterministic “keep latest” logic; add a tie-breaker column.
  • Use QUALIFY in Databricks SQL or Snowflake for shorter queries.
  • For streaming, always pair deduplication with a watermark to control state size.

FAQ

Is distinct() the same as dropDuplicates()?

Yes, when dropDuplicates() is called without any columns. With a column list, dropDuplicates() checks only those columns.

Does dropDuplicates() keep the first row?

Not reliably. Spark processes data in parallel, so the kept row can change between runs. Use ROW_NUMBER() when it matters.

Why not use RANK() to deduplicate?

RANK() gives the same number to tied rows, so filtering rank 1 can still return duplicates. ROW_NUMBER() always gives unique numbers.

How do I find duplicate records before deleting them?

Group by the key columns and use HAVING COUNT(*) > 1. In PySpark: df.groupBy("order_id").count().filter("count > 1").

Does deduplication cause a shuffle in Spark?

Yes. distinct(), dropDuplicates() and window functions with partitionBy are wide transformations, so Spark shuffles data across the cluster.

Related reading: Small files problem in Spark and Delta Lake, Adaptive Query Execution in Spark and PySpark UDF vs Pandas UDF.

Sources

Article Categories:
Educations

Leave a Reply

Your email address will not be published. Required fields are marked *