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.
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|
# +-----+---+------+Only dropDuplicates accepts a subset of columns. Spark then compares rows on those columns alone, so the age=10 row also collapses into one row per (name, height). distinct() takes no arguments and compares every column. dropna removes rows with nulls, and groupBy returns grouped data that has to be aggregated, not deduplicated rows.
Source: docs.databricks.comCheckpoint 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?
Correct answer: B — df.distinct() to compare every column across each row and keep only one copy of rows that are identical in all fields
- A. Restricting to a single column like
event_iddeduplicates on that key alone, so two rows sharing an ID but differing elsewhere would still be collapsed into one, which is not the same as removing exact full-row duplicates. - B. Correct —
distinct()considers all columns when comparing rows and returns only unique rows, so exact duplicate rows created by upstream retries are removed while distinct rows are preserved. - C. Grouping by every column and filtering to a count of one would drop rows that appear more than once instead of keeping one copy of them, so any row written twice by a retry would be discarded entirely rather than deduplicated.
- D.
dropna()removes rows containing null values and has no relationship to identifying or removing rows that are byte-for-byte duplicates of each other.
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?
On a stream, dropDuplicates keeps everything it has seen across triggers as state. A watermark applied before it tells Spark how late a duplicate can arrive, so Spark can limit that state. The trade-off is that data older than the watermark is dropped rather than checked, which rules out the spill-to-disk option and the options that keep late records.
“You can use withWatermark to limit how late the duplicate data can be and the system will accordingly limit the state.”Source: docs.databricks.com
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?
Correct answer: A — Sort the DataFrame by updated_at in descending order and apply dropDuplicates(["ticket_id"]), since sorting first controls which row per key is retained
- A. Correct — ordering the DataFrame by
updated_atdescending before callingdropDuplicates(["ticket_id"])makes the retained row for each key the one encountered first in that order, which is the most recently updated ticket. - B.
distinct()compares every column, so two rows sharing aticket_idbut differing inupdated_atare already distinct rows and both would be kept, leaving the duplicateticket_idproblem unresolved. - C. Deduplicating on both
ticket_idandupdated_attogether only removes rows that are exact duplicates on that pair, so the two differently-timestamped copies of the same ticket would both survive. - D. Filtering to tickets that appear exactly once and unioning that back with the original data would reintroduce every duplicate row rather than resolving them down to the latest update.
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.
| Function | Counts | Nulls | Precision |
|---|---|---|---|
| count("*") (row count) | Every row | Rows with nulls still count | Exact |
| count(col) | Non-null values in col, repeats included | Skipped | Exact |
| count_distinct(col, *cols) | Unique values of one or more columns | Skipped | Exact |
| approx_count_distinct(col, rsd) | Estimated unique values | Skipped | Estimate 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.
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.
count("*") counts every row, and count(col) counts only the non-null values in that column, repeats included. count_distinct gives an exact unique count. approx_count_distinct gives a cheaper estimate, which suits a dashboard but not an audit.
“using approximation for aggregates can accelerate query processing and reduce costs when you don't require precise results.”Source: docs.databricks.com
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?
Correct answer: B — countDistinct("customer_id"), which computes the exact number of unique values in the column by evaluating every row
- A.
approx_count_distincttrades exactness for speed by using an approximation algorithm, so its result can differ slightly from the true distinct count and is unsuitable when an audit requires a precise figure. - B. Correct —
countDistinctreturns the exact number of unique values in the specified column, which is the guarantee a regulatory audit figure requires. - C.
counton a column tallies non-null rows without regard to whether the same value repeats, so it would overcount whenever a customer places more than one order. - D.
meancomputes a numeric average of the identifier values, which is not a meaningful count of unique customers and is the wrong aggregation entirely for this requirement.
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().
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.
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?
GroupedData.count() counts the records in each group, so rows with nulls still count. sf.count(col) inside agg() counts only the non-null values in that column, so the difference is the number of null emails in the group. It does not count distinct values, and agg() does not drop rows that contain nulls.
“count() | Counts the number of records for each group.”Source: docs.databricks.com
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.
| Aspect | describe() | summary() |
|---|---|---|
| Default statistics | count, mean, stddev, min, max | count, mean, stddev, min, 25%, 50%, 75%, max |
| What the arguments select | Columns, e.g. describe(['age']) | Statistics, e.g. summary("count", "min", "25%") |
| Percentiles | None | Any approximate percentile written as a percentage |
| Choosing columns | Pass column names | select() the columns first |
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|
# +-------+---+------+------+summary() takes the names of statistics as arguments and can compute approximate percentiles such as 25% and 75%. describe() takes column names as arguments and returns only count, mean, stddev, min and max, so it never produces percentile rows. agg() and groupBy() don't accept statistic names like these.
Source: docs.databricks.comPractise it for real
See in a notebook how full-row deduplication, key-based deduplication and an approximate distinct count differ
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.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.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.
“Returns a new DataFrame containing the distinct rows in this DataFrame.”
↩︎ Full-row duplicates versus key duplicates - 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.
“Returns a new Column for distinct count of col or cols.”
↩︎ Counting rows, values, and distinct values - 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 - 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 - 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 - 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 - 8.
“Aggregate on the entire DataFrame without groups (shorthand for df.groupBy().agg()).”
↩︎ Grouped aggregates with groupBy().agg() and mean - 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 - 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 - 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