CertSafari
    Databricks Certified Data Engineer Associate· Lessons

    Domain 3 · Lesson 13/33

    Deduplicating and aggregating Spark DataFrames

    Perform data deduplication operations and aggregate operations on DataFrames, such as count, approximate count distinct, and mean, summary

    17 min read
    3.14% of exam
    11 sources
    Published 22 Oct 2026
    Docs as of 30 Sep 2026

    What you will be able to do

    • Choose between distinct() and dropDuplicates(subset) for a given definition of a duplicate row
    • Keep the newest row per key, and use a watermark to limit the state a streaming deduplication keeps
    • Tell apart a row count, count(col), count_distinct and approx_count_distinct, and pick the right one when precision matters
    • Compute grouped aggregates with groupBy().agg() and predict how mean treats nulls
    • Profile a whole DataFrame with summary() or describe()

    Key concept

    Comparison columns — Every deduplication decision depends on which columns decide that two rows are the same. If you compare all columns, only exact copies are removed. If you compare a subset, Spark keeps one row per key, whatever the other columns contain.

    1.Full-row duplicates versus key duplicates

    Duplicates reach a bronze table in two forms, and each one needs a different tool. In the first form, an upstream retry writes the same event twice, so the two rows match in every field. In the second form, two rows share a business key such as ticket_id but differ elsewhere, for example in a timestamp. Removing duplicates before data reaches silver means first deciding which of these two forms you have.

    distinct() handles exact copies. It returns a new DataFrame that contains only the distinct rows, and two rows count as the same only when every column matches. Calling dropDuplicates() with no arguments does the same thing, because its subset parameter defaults to all columns. Pass a list such as dropDuplicates(["event_id"]) and the comparison narrows to those columns. Spark then keeps one row per key, and the values in every other column come from whichever row survived.

    With no arguments, dropDuplicates removes only the exact copy. With a subset, it collapses the rows to one per (name, height), so the age=10 row is lost too.python
    df = spark.createDataFrame([
        Row(name='Alice', age=5, height=80),
        Row(name='Alice', age=5, height=80),
        Row(name='Alice', age=10, height=80)
    ])
    
    df.dropDuplicates().show()
    # +-----+---+------+
    # | name|age|height|
    # +-----+---+------+
    # |Alice|  5|    80|
    # |Alice| 10|    80|
    # +-----+---+------+
    
    df.dropDuplicates(['name', 'height']).show()
    # +-----+---+------+
    # | name|age|height|
    # +-----+---+------+
    # |Alice|  5|    80|
    # +-----+---+------+

    That second output shows the risk of using a key subset on retry duplicates. If two different events happened to share an event_id, dropDuplicates(["event_id"]) would quietly throw one of them away without looking at what it contained. When the duplicates come from retries, the right test is "identical in every field", and that is what distinct() checks.

    Two other approaches look like deduplication but are not. Grouping by every column, counting, and keeping groups where count == 1 keeps only the rows that were never repeated, so every retried event loses all of its copies rather than keeping one. dropna() removes rows that contain nulls and has nothing to do with repetition. It belongs with null handling during cleaning.

    Checkpoint 1 of 8· Fill the gap

    The second call returns a single row: one row per (name, height) key. Which method fills the blank?

    df = spark.createDataFrame([
        Row(name='Alice', age=5, height=80),
        Row(name='Alice', age=5, height=80),
        Row(name='Alice', age=10, height=80)
    ])
    
    df.dropDuplicates().show()
    # +-----+---+------+
    # | name|age|height|
    # +-----+---+------+
    # |Alice|  5|    80|
    # |Alice| 10|    80|
    # +-----+---+------+
    
    df. ? (['name', 'height']).show()
    # +-----+---+------+
    # | name|age|height|
    # +-----+---+------+
    # |Alice|  5|    80|
    # +-----+---+------+

    Checkpoint 2 of 8· Exam question

    A data engineer loads a bronze table of clickstream events where upstream retries occasionally write the exact same row multiple times across all columns. Before writing to silver, the engineer wants to remove full-row duplicates while keeping the rest of the pipeline unchanged. Which transformation should the engineer apply to the DataFrame?

    Sources12

    2.Keeping the newest row per key, and bounding streaming state

    When copies of a key differ, you also have to choose which copy to keep. Suppose a support-ticket table has several rows for one ticket_id, each with a different updated_at. The standard approach sorts the DataFrame by updated_at in descending order and then calls dropDuplicates(["ticket_id"]). The comparison uses only ticket_id, so one row per ticket remains, and sorting first puts the newest version at the front of each key.

    All three survive. Adding updated_at to the subset makes it part of the duplicate test. Because the copies differ in exactly that column, no two of them count as duplicates, and nothing is removed. A rule of thumb follows: the subset should contain the columns that define identity, never the column you are using to break ties. distinct() fails here for the same reason, since the copies are not equal in every field.

    In streaming, deduplication has a memory cost. On a static batch DataFrame, dropDuplicates simply drops rows. On a streaming DataFrame, Spark cannot know whether a key will show up again in the next micro-batch, so it keeps all the data it has seen, across triggers, as intermediate state. Without a limit, that state grows for as long as the stream runs.

    A watermark puts a limit on that state. Calling withWatermark before dropDuplicates tells Spark how late a duplicate can arrive, and Spark trims the stored state to match. This has a cost: records older than the watermark are dropped so that no duplicates can slip through. A watermark that is too tight therefore loses genuinely late data, while one that is too loose keeps more state than you need.

    Checkpoint 3 of 8· Check yourself

    A Structured Streaming job deduplicates click events with dropDuplicates(["event_id"]). After several weeks of running, its state store is still growing. What change bounds the state, and what does it cost?

    Checkpoint 4 of 8· Exam question

    A silver table of customer support tickets contains a ticket_id column that should be unique, but a schema issue upstream produced duplicate ticket_id values where the associated updated_at timestamp differs between copies. The engineer wants to keep only the row with the latest updated_at for each ticket_id. Which approach accomplishes this?

    Sources2

    3.Counting rows, values, and distinct values

    "How many?" can mean four different things, and Spark has a separate function for each. Counting with * counts rows. count(col) counts the non-null values in one column. A distinct count counts unique values. An approximate distinct count estimates the number of unique values without guaranteeing the exact figure. On a column of None, "a", "b", "c", the row count is 4 but count(alphabets) is 3, because the null is skipped.

    Four ways to count, and what each one returns
    FunctionCountsNullsPrecision
    count("*") (row count)Every rowRows with nulls still countExact
    count(col)Non-null values in col, repeats includedSkippedExact
    count_distinct(col, *cols)Unique values of one or more columnsSkippedExact
    approx_count_distinct(col, rsd)Estimated unique valuesSkippedEstimate within rsd (default 0.05)

    count_distinct gives the exact number of unique values in one column or in a combination of columns. On the values 1, 1, 3 it returns 2. Exam questions use the camelCase name countDistinct, while the function reference uses count_distinct.

    approx_count_distinct gives up some precision to gain speed. Its rsd parameter sets the maximum allowed relative standard deviation and defaults to 0.05. Approximate aggregates can make queries faster and cheaper when you do not need a precise result. Asking for very high precision undoes that advantage: below an rsd of 0.01, count_distinct is the more efficient choice.

    Neither estimate equals the true 100,000, and the looser rsd of 0.1 lands further from itpython
    from pyspark.sql import functions as sf
    spark.range(100000).agg(
        sf.approx_count_distinct("id").alias('with_default_rsd'),
        sf.approx_count_distinct("id", 0.1).alias('with_rsd_0.1')
    ).show()
    
    +----------------+------------+
    |with_default_rsd|with_rsd_0.1|
    +----------------+------------+
    |           95546|      102065|
    +----------------+------------+

    That gap decides which function to use. For a dashboard tile that tracks daily unique visitors, an error of a few percent is acceptable, and approx_count_distinct saves time and money. For a regulatory audit figure that must match the true number of customers, only the exact count_distinct is acceptable. count("customer_id") would count repeat customers more than once, and averaging an identifier column does not produce a count of anything.

    Checkpoint 5 of 8· Match them up

    A customers table has a nullable email column and repeat rows for some customer_id values. Match each reporting need to the aggregate that meets it.

    Tap a term, then the definition that fits it.

    Checkpoint 6 of 8· Exam question

    A data engineer needs to know the exact number of distinct customer IDs in a gold-layer sales table that will be used for a regulatory audit report, where the reported figure must match the true count precisely. Which function should the engineer use to compute this value?

    Sources3456

    4.Grouped aggregates with groupBy().agg() and mean

    groupBy turns a DataFrame into grouped data, and each aggregate is then computed once per group. The grouped object has shortcut methods (count(), sum, min, max, avg, mean) plus agg(), which accepts either a dictionary such as {"age": "max"} or a list of Column expressions such as sf.min("age"). Calling df.agg(...) without groupBy aggregates the whole DataFrame as a single group. It is shorthand for df.groupBy().agg().

    GroupedData.count() returns the number of records in each grouppython
    df = spark.createDataFrame(
        [(2, "Alice"), (3, "Alice"), (5, "Bob"), (10, "Bob")], ["age", "name"])
    df.groupBy("name").count().sort("name").show()
    
    +-----+-----+
    | name|count|
    +-----+-----+
    |Alice|    2|
    |  Bob|    2|
    +-----+-----+

    The two counts behave differently. GroupedData.count() counts records per group, so a row with nulls still counts. sf.count(col) used inside agg() counts only the non-null values in that column. In the same groupBy they can return different numbers, and the difference is the number of nulls in each group.

    mean skips the null age and averages only 2 and 4python
    import pyspark.sql.functions as sf
    df = spark.createDataFrame([(1982, None), (1990, 2), (2000, 4)], ["birth", "age"])
    df.select(sf.mean("age")).show()
    
    +--------+
    |avg(age)|
    +--------+
    |     3.0|
    +--------+

    mean and avg are aliases, which is why the output column above is named avg(age). Because nulls are ignored, a column that is mostly null can still produce a confident-looking average based on only a few rows. Put count(col) next to mean(col) in the same agg() when you need to see how many values the average is based on.

    Checkpoint 7 of 8· Check yourself

    Two queries run against the same orders table. df.groupBy("region").count() reports 120 rows for EMEA, but df.groupBy("region").agg(sf.count("email")) reports 97 for EMEA. What explains the gap?

    Sources789

    5.Profiling a whole DataFrame with summary and describe

    summary() and describe() compute standard statistics for every numeric and string column in one call, which saves writing an agg() with many expressions while you explore data. Both return a DataFrame with one row per statistic and one column per input column. describe() returns count, mean, stddev, min and max. summary() adds approximate percentiles and lets you choose which statistics to compute.

    describe() versus summary()
    Aspectdescribe()summary()
    Default statisticscount, mean, stddev, min, maxcount, mean, stddev, min, 25%, 50%, 75%, max
    What the arguments selectColumns, e.g. describe(['age'])Statistics, e.g. summary("count", "min", "25%")
    PercentilesNoneAny approximate percentile written as a percentage
    Choosing columnsPass column namesselect() the columns first
    summary() with selected statistics: select() limits the columns, and the arguments name the statisticspython
    df.select("age", "weight", "height").summary("count", "min", "25%", "75%", "max").show()
    # +-------+---+------+------+
    # |summary|age|weight|height|
    # +-------+---+------+------+
    # |  count|  3|     3|     3|
    # |    min| 11|  37.8| 142.2|
    # |    25%| 11|  37.8| 142.2|
    # |    75%| 13|  44.1| 150.5|
    # |    max| 13|  44.1| 150.5|
    # +-------+---+------+------+

    Both methods are intended for exploratory analysis, and the schema of the DataFrame they return is not guaranteed to stay backward compatible. A notebook cell that checks a new silver table is a good use for them. A production job that writes summary() output to a table and has downstream readers parsing its columns is not. For a reported figure, write an explicit agg() with named columns.

    Checkpoint 8 of 8· Fill the gap

    This profiling cell names the statistics it wants, and the output includes 25% and 75% rows. Which DataFrame method goes in the blank?

    df.select("age", "weight", "height"). ? ("count", "min", "25%", "75%", "max").show()
    # +-------+---+------+------+
    # |summary|age|weight|height|
    # +-------+---+------+------+
    # |  count|  3|     3|     3|
    # |    min| 11|  37.8| 142.2|
    # |    25%| 11|  37.8| 142.2|
    # |    75%| 13|  44.1| 150.5|
    # |    max| 13|  44.1| 150.5|
    # +-------+---+------+------+

    Sources1011

    Practise it for real

    See in a notebook how full-row deduplication, key-based deduplication and an approximate distinct count differ

    1. 1.Create the three-row DataFrame of Row(name='Alice', ...) records, with two identical rows (age=5) and one with age=10, then run df.dropDuplicates().show().

      Why: With no subset, every column is compared, so only the exact copy is removed.

      You should see: Two rows: Alice with age 5 and Alice with age 10, both with height 80.

    2. 2.Run df.dropDuplicates(['name', 'height']).show() on the same DataFrame.

      Why: Narrowing the comparison to name and height makes all three rows duplicates of one another.

      You should see: One row: Alice, age 5, height 80.

    3. 3.Create spark.createDataFrame([1,2,2,3], "int") and run df.agg(sf.approx_count_distinct("value")).show().

      Why: This calls an approximate aggregate through df.agg(), which aggregates the whole DataFrame as one group.

      You should see: A single column named approx_count_distinct(value) with the value 3.

    Stuck? Get a nudge

    If step 2 still shows two rows, check that you passed a list of column names rather than calling dropDuplicates() with no arguments.

    Sources

    (11)

    Every claim above is drawn from one of these pages, quoted as it was written on the date shown.

    1. 1.
      “Returns a new DataFrame containing the distinct rows in this DataFrame.”
      ↩︎ Full-row duplicates versus key duplicates
    2. 2.
      “Return a new DataFrame with duplicate rows removed, optionally only considering certain columns.”
      ↩︎ Full-row duplicates versus key duplicates
      “For a streaming DataFrame, it will keep all data across triggers as intermediate state to drop duplicates rows.”
      ↩︎ Keeping the newest row per key, and bounding streaming state
      “In addition, data older than watermark will be dropped to avoid any possibility of duplicates.”
      ↩︎ Keeping the newest row per key, and bounding streaming state
      “List of columns to use for duplicate comparison (default All columns).”
      ↩︎ Key concept
      “List of columns to use for duplicate comparison (default All columns).”
      ↩︎ Exam trap 1
      “You can use withWatermark to limit how late the duplicate data can be and the system will accordingly limit the state.”
      ↩︎ Exam trap 2
      “You can use withWatermark to limit how late the duplicate data can be and the system will accordingly limit the state.”
      ↩︎ Checkpoint
    3. 4.
      “The maximum allowed relative standard deviation (default = 0.05).”
      ↩︎ Counting rows, values, and distinct values
      “If rsd < 0.01, it would be more efficient to use count_distinct.”
      ↩︎ Exam trap 4
      “Returns a new Column, which estimates the approximate distinct count of elements in a specified column or a group of columns.”
      ↩︎ Prediction
    4. 5.
      “using approximation for aggregates can accelerate query processing and reduce costs when you don't require precise results”
      ↩︎ Counting rows, values, and distinct values
      “using approximation for aggregates can accelerate query processing and reduce costs when you don't require precise results.”
      ↩︎ Checkpoint
    5. 6.
      “Count non-null values in a specific column”
      ↩︎ Counting rows, values, and distinct values
      “Count non-null values in a specific column”
      ↩︎ Exam trap 3
    6. 7.
      “Counts the number of records for each group.”
      ↩︎ Grouped aggregates with groupBy().agg() and mean
      “Computes average values for each numeric column for each group. mean is an alias.”
      ↩︎ Grouped aggregates with groupBy().agg() and mean
      “count() | Counts the number of records for each group.”
      ↩︎ Checkpoint
    7. 8.
      “Aggregate on the entire DataFrame without groups (shorthand for df.groupBy().agg()).”
      ↩︎ Grouped aggregates with groupBy().agg() and mean
    8. 9.
      “Nulls within the group are ignored. If a group is empty or consists only of nulls the result is NULL.”
      ↩︎ Grouped aggregates with groupBy().agg() and mean
    9. 10.
      “Available statistics are: count, mean, stddev, min, max, arbitrary approximate percentiles specified as a percentage (e.g., 75%).”
      ↩︎ Profiling a whole DataFrame with summary and describe
      “we make no guarantee about the backward compatibility of the schema of the resulting DataFrame”
      ↩︎ Profiling a whole DataFrame with summary and describe
    10. 11.
      “Use summary for expanded statistics and control over which statistics to compute.”
      ↩︎ Profiling a whole DataFrame with summary and describe
      “Use summary for expanded statistics and control over which statistics to compute.”
      ↩︎ Exam trap 5

    Spotted a mistake, or was something unclear? Tell us.