← BuildandTeach Tech Tutorials posts

Published · By Henry Palma

Databricks Data Engineer Associate Exam Prep, Lesson 9: Deduplication and Aggregates in PySpark (dropDuplicates, row_number, count distinct)

Databricks Data Engineer Associate exam prep: dedupe an orders change feed with row_number, avoid dropDuplicates traps, and choose the right count.

Databricks Data Engineer Associate Exam Prep, Lesson 9: Deduplication and Aggregates in PySpark (dropDuplicates, row_number, count distinct)

Exam-style question: An orders change data capture (CDC) feed has two rows for order 5002: amount 30.00 at 10:00 on Nov 2, and a late update to 36.00 that arrives at 7:05 on Nov 4. You run orderscdc.dropDuplicates(["orderid"]). Which amount does Spark keep for order 5002? Spark does not guarantee either one. dropDuplicates keeps one row per key, but it has no sort argument, so you cannot tell it to keep the latest change. To keep the latest, number the rows with rownumber() over a window partitioned by orderid and ordered by change_ts descending, then keep row 1. This post follows Lesson 9 of the Databricks Data Engineer Associate exam prep series, in Section 3 of the August 2026 exam guide, Data Transformation and Modeling (22% of the exam).

Watch on YouTube

Video thumbnail
Video thumbnail

The notebook and cheat sheet are in the A09 folder on GitHub. The PDF cheat sheet is in the same folder. This is independent study material, not official Databricks training.

The exam objective

Section 3 of the exam guide lists this objective: perform data deduplication operations and aggregate operations on DataFrames, such as count, approximate count distinct, and mean, summary.

In practice, that comes down to three questions. What is the business key that makes a row unique? When there are several rows for one key, which one should survive? And does this count need to be exact, distinct, or just close?

Everything here runs in Databricks Free Edition, in a Python notebook on serverless compute with Unity Catalog. The outputs in this post were checked with a local Apache Spark 4.0 run of the same code, not on Databricks.

The scenario: a late-arriving orders feed

The retail dataset from Lesson 8 gets a new table. orderscdc is a change feed from the order system. Every time an order is created or changed, the feed sends the whole row again with a changets timestamp. Rows can arrive late, and the same file is sometimes sent twice.

orders_cdc (8 rows, in arrival order):

| orderid | customerid | orderdate | amount | op | changets | |---|---|---|---|---|---| | 5001 | 101 | 2026-11-02 | 24.00 | insert | 2026-11-02 09:00:00 | | 5002 | 102 | 2026-11-02 | 30.00 | insert | 2026-11-02 10:00:00 | | 5001 | 101 | 2026-11-02 | 28.50 | update | 2026-11-02 15:30:00 | | 5003 | 103 | 2026-11-03 | 13.50 | insert | 2026-11-03 08:00:00 | | 5003 | 103 | 2026-11-03 | 13.50 | insert | 2026-11-03 08:00:00 | | 5004 | 101 | 2026-11-03 | 40.00 | insert | 2026-11-03 09:15:00 | | 5005 | 104 | 2026-11-03 | 18.00 | insert | 2026-11-03 11:45:00 | | 5002 | 102 | 2026-11-02 | 36.00 | update | 2026-11-04 07:05:00 |

Three kinds of duplicates are mixed in here:

  • Order 5003 is an exact duplicate. Every column matches.
  • Order 5001 has an update on the same day. The amount went from 24.00 to 28.50.
  • Order 5002 has a late update. It belongs to Nov 2, but the change arrived on Nov 4.

The job: keep one row per orderid, the latest change, then report daily order count and average order value. amount is DECIMAL(10,2) and changets is a timestamp.

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

orderscdc = spark.read.table("orderscdc") orders_cdc.count() # 8 ```

distinct and dropDuplicates

distinct() removes rows that are identical in every column. dropDuplicates() with no arguments does the same thing:

orders_cdc.distinct().count()          # 7
orders_cdc.dropDuplicates().count()    # 7

Only the exact copy of order 5003 is gone. Orders 5001 and 5002 still have two rows each, because their amounts and timestamps differ.

dropDuplicates also takes a list of columns. Then it keeps one row per value of those columns:

orders_cdc.dropDuplicates(["order_id"]).count()   # 5

Five rows, one per order. That looks right, but look at which rows survived. In the local Spark run, order 5001 kept the old 24.00 row and order 5002 kept the new 36.00 row. One old, one new. A second local run, of the lesson notebook, kept the old 30.00 row for order 5002 instead.

That is the trap. dropDuplicates has no argument for sort order, so you cannot ask it for the latest row. In the query plan, Spark implements it as an aggregation that takes first() of each column per key, and the PySpark docs note that first() is non-deterministic because row order may change after a shuffle. Sorting the DataFrame before dropDuplicates does not turn that into a guarantee. If you need a specific row, choose it yourself.

The key matters just as much. Two easy mistakes:

orders_cdc.dropDuplicates(["customer_id"]).count()            # 4 (wrong key: one order per customer)
orders_cdc.dropDuplicates(["order_id", "change_ts"]).count()  # 7 (key too wide: updates survive)

Customer 101 placed two orders, 5001 and 5004, so deduplicating on customerid silently deletes a real order. Adding changets to the key makes every update look unique, so nothing but the exact copy is removed.

Keep the latest change with row_number

To keep the latest row per key, number the rows inside each key, newest first, and keep number 1:

w = Window.partitionBy("order_id").orderBy(F.col("change_ts").desc())

orderslatest = (orderscdc .withColumn("rn", F.row_number().over(w)) .filter("rn = 1") .drop("rn"))

orders_latest.count() # 5 ```

rownumber() gives 1, 2, 3 and so on within each orderid, in the window's sort order. Ordering by change_ts descending puts the latest change at 1.

| orderid | orderdate | amount | op | change_ts | |---|---|---|---|---| | 5001 | 2026-11-02 | 28.50 | update | 2026-11-02 15:30:00 | | 5002 | 2026-11-02 | 36.00 | update | 2026-11-04 07:05:00 | | 5003 | 2026-11-03 | 13.50 | insert | 2026-11-03 08:00:00 | | 5004 | 2026-11-03 | 40.00 | insert | 2026-11-03 09:15:00 | | 5005 | 2026-11-03 | 18.00 | insert | 2026-11-03 11:45:00 |

Both updates won, and the late update for 5002 still lands on its real order date, Nov 2. If two rows for one key can share the same change_ts, add a second column to the orderBy as a tiebreaker. Here the only tie is the exact copy of 5003, so either row gives the same result.

The same thing in SQL:

SELECT order_date,
       COUNT(*)              AS order_count,
       ROUND(AVG(amount), 2) AS avg_order_value
FROM (
  SELECT *,
         ROW_NUMBER() OVER (PARTITION BY order_id ORDER BY change_ts DESC) AS rn
  FROM orders_cdc
)
WHERE rn = 1
GROUP BY order_date
ORDER BY order_date;

A note for streaming: on a streaming DataFrame, dropDuplicates keeps all keys it has seen as state across triggers. The docs recommend withWatermark() to limit how late duplicates can be, so the state does not grow forever.

Daily order count and average order value

Aggregate after you dedupe, never before:

daily = (orders_latest
    .groupBy("order_date")
    .agg(F.count("*").alias("order_count"),
         F.round(F.avg("amount"), 2).alias("avg_order_value"))
    .orderBy("order_date"))

| orderdate | ordercount | avgordervalue | |---|---|---| | 2026-11-02 | 2 | 32.25 | | 2026-11-03 | 3 | 23.83 |

Nov 2 is (28.50 + 36.00) / 2 = 32.25. Nov 3 is (13.50 + 40.00 + 18.00) / 3 = 23.83.

Run the same aggregation on the raw feed and both numbers are wrong:

| orderdate | ordercount | avgordervalue | |---|---|---| | 2026-11-02 | 4 | 29.63 | | 2026-11-03 | 4 | 21.25 |

Nov 2 counts two orders twice and averages in the stale 24.00 and 30.00 amounts. Nov 3 counts order 5003 twice. Nothing errors. The dashboard is just wrong.

F.avg and F.mean are the same function. Both skip NULL values.

count, count distinct and approxcountdistinct

Three counts the exam likes to mix up:

orders_cdc.select(
    F.count("*").alias("rows"),                              # 8
    F.count("order_id").alias("count_order_id"),             # 8
    F.count_distinct("order_id").alias("distinct_orders"),   # 5
    F.approx_count_distinct("order_id").alias("approx"),     # 5
).show()
  • count("*") counts rows. count("orderid") counts non-NULL values in that column. If one row had a NULL orderid, the first would be 9 and the second 8.
  • count_distinct (also spelled countDistinct, or COUNT(DISTINCT ...) in SQL) is exact. It also skips NULLs.
  • approxcountdistinct is an estimate. Databricks documents it as using the HyperLogLog++ algorithm, accurate within 5% by default. The rsd argument sets the maximum relative standard deviation, default 0.05.

On five keys the estimate happens to be exact. On larger data it usually is not. Over 100,000 distinct IDs, the local run returned:

spark.range(100000).agg(
    F.approx_count_distinct("id"),        # 95546  (default rsd 0.05)
    F.approx_count_distinct("id", 0.1),   # 102065
    F.count_distinct("id"),               # 100000
)

Use approxcountdistinct when a close answer on very large data is fine, such as unique visitors on a dashboard. Use countdistinct when the number has to be exact, such as orders billed. The PySpark docs say that if you need an rsd below 0.01, countdistinct is the more efficient choice.

describe and summary

For a quick profile of a column, describe() returns count, mean, stddev, min and max. summary() returns the same plus the 25%, 50% and 75% percentiles, which are approximate:

orders_latest.select("amount").summary().show()

| summary | amount | |---|---| | count | 5 | | mean | 27.200000 | | stddev | 11.350110131624273 | | min | 13.50 | | 25% | 18.0 | | 50% | 28.5 | | 75% | 36.0 | | max | 40.00 |

You can pass the statistics you want, for example summary("count", "mean", "min", "max"). The docs describe summary as meant for exploratory analysis, so use groupBy().agg() for numbers that feed a report.

Dedup checklist

Before you dedupe any feed:

  1. Business key. What makes a row unique for the business? Here it is orderid, not customerid, and not orderid plus changets.
  2. Sort. Which column says which row is newest? Here it is change_ts. Add a tiebreaker if two rows can share it.
  3. Keep latest. Use row_number() over partitionBy(key).orderBy(sort desc) and keep rn = 1. Use dropDuplicates(key) only when any surviving row is acceptable, such as exact copies.
  4. Check the counts. count() after dedupe should equal count_distinct(key) before it. Here both are 5.
  5. Then aggregate. Count, average and sum on the deduplicated DataFrame.

The reusable snippet:

def keep_latest(df, key_cols, ts_col):
    w = Window.partitionBy(*key_cols).orderBy(F.col(ts_col).desc())
    return (df.withColumn("rn", F.row_number().over(w))
              .filter("rn = 1")
              .drop("rn"))

orderslatest = keeplatest(orderscdc, ["orderid"], "change_ts")

assert orderslatest.count() == orderscdc.select(F.countdistinct("orderid")).first()[0]

daily = (orderslatest.groupBy("orderdate") .agg(F.count("*").alias("ordercount"), F.round(F.avg("amount"), 2).alias("avgorder_value"))) ```

Practice exam-style question

A data engineer must report the exact number of distinct customers who placed an order last month, for an invoice to a partner. The orders table has 2 billion rows. Which expression should they use?

  • A) F.approxcountdistinct("customer_id")
  • B) F.count("customer_id")
  • C) F.countdistinct("customerid")
  • D) orders.dropDuplicates(["order_id"]).count()

Answer: C. The number must be exact and distinct, so countdistinct is the right function. A is an estimate, accurate within about 5% by default, which is fine for a dashboard but not for an invoice. B counts every non-NULL customerid, so a customer with ten orders counts ten times. D counts unique orders, not customers.

Key takeaways

  • distinct() and dropDuplicates() with no arguments remove only rows that match in every column.
  • dropDuplicates(["key"]) keeps one row per key, but you cannot choose which one. Pick the key carefully: too narrow deletes real rows, too wide keeps the duplicates.
  • To keep the latest change, use row_number() over a window partitioned by the business key and ordered by the change timestamp descending, then keep row 1.
  • count("*") counts rows, count(col) skips NULLs, countdistinct is exact, and approxcount_distinct is an estimate (default within 5%).
  • Memory trick: dropDuplicates keeps a row. row_number keeps the right row. Business key, sort, keep latest, then aggregate.

Next lesson (Lesson 10): Gold layer views, materialized views and streaming tables.

Check your understanding

1. A DataFrame has 8 rows. One row is an exact copy of another, and two orders each have an older and a newer version. What does df.distinct().count() return?

  • A) 5
  • B) 6
  • C) 7
  • D) 8

2. You need each orderid to keep its latest change by changets. Which approach guarantees that?

  • A) df.dropDuplicates(["order_id"])
  • B) df.orderBy(F.col("changets").desc()).dropDuplicates(["orderid"])
  • C) rownumber() over Window.partitionBy("orderid").orderBy(F.col("change_ts").desc()), then keep row 1
  • D) df.dropDuplicates(["orderid", "changets"])

3. A column has 8 values, one of them NULL. What does F.count("col") return?

  • A) 7
  • B) 8
  • C) 9
  • D) It raises an error on NULL

4. What is true about approxcountdistinct with default settings?

  • A) It always returns the exact distinct count
  • B) It returns an estimate, accurate within about 5% by default
  • C) It counts NULL values as one distinct value
  • D) It only works in SQL, not in PySpark

5. Customer 101 placed orders 5001 and 5004. What happens if you dedupe the orders feed with dropDuplicates(["customer_id"])?

  • A) Nothing, because each order still has its own row
  • B) One of customer 101's real orders is removed
  • C) Spark raises an error because customer_id is not unique
  • D) Both of customer 101's orders are removed

Answer key

  1. C. distinct removes only the exact copy. The older and newer versions differ in amount and timestamp, so they stay.
  2. C. Only the window with row_number lets you choose the row. dropDuplicates has no sort argument, and sorting first is not a guarantee.
  3. A. count(col) skips NULLs. count("*") would return 8.
  4. B. It uses HyperLogLog++ and its default maximum relative standard deviation is 0.05. Use count_distinct for an exact answer.
  5. B. The key is too narrow. One row per customer means one of the two real orders is dropped without an error.

Have an idea, question, or feedback?

We'd genuinely like to hear from you.