Series vs DataFrame, WHERE vs HAVING, and Finding Repeated Emails
SQL & DataModel answerLast updated
Three short data-engineering questions: contrast pandas Series and DataFrame, explain when SQL applies WHERE versus HAVING, and write a query that reports emails occurring more than once.
Answer the three short questions below, as you would in a screening conversation for an entry-level data engineering role.
Part 1: pandas
What distinguishes a pandas Series from a pandas DataFrame? Give one realistic situation where you would reach for each.
Part 2: SQL filtering
Explain how WHERE differs from HAVING. When is each one the right choice, and why can't one always stand in for the other?
Part 3: Query
Consider this table:
customer_events
| Column | Type |
|---|---|
event_id | BIGINT |
customer_email | STRING |
source_system | STRING |
created_at | TIMESTAMP (stored in UTC) |
Write a SQL query that finds every customer_email that shows up more than once across the entire table. Return:
customer_emailduplicate_count(how many times that email appears)
Only emails with a count above 1 should be returned.
Besides the query, state any assumptions or edge cases you would raise (for example NULL values or inconsistent formatting), and describe how you would do the same thing in pandas.
Hints
Hint 1
Think of a Series as one labeled column and a DataFrame as several such columns sharing a row index. What does `df['col']` return versus `df[['col']]`?
Hint 2
Write out the logical order in which SQL evaluates clauses: FROM, WHERE, GROUP BY, aggregates, HAVING, SELECT. At which point do group counts first exist?
Hint 3
For the query, group by the email, count rows per group, and filter on the count after grouping. Then ask what happens to rows where the email is NULL, and whether the timestamp matters at all.
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
1. Series vs DataFrame
- A Series is a one-dimensional labeled array: a sequence of values with a single dtype and an index.
- A DataFrame is a two-dimensional labeled table. It behaves like a set of Series that share one row index, and each column may have its own dtype.
df["customer_email"] returns a Series, while df[["customer_email"]] returns a one-column DataFrame.
Typical uses
- Series: operating on a single variable, such as
df["amount"].mean(),df["customer_email"].str.lower(), or holding the output ofvalue_counts(). - DataFrame: handling records with several attributes, such as loading a Parquet file of events, joining it with a customers table, or grouping by
source_systemand aggregating multiple columns.
Short version: a Series is a column, a DataFrame is a table of aligned columns.
2. WHERE vs HAVING
They filter at different points in query evaluation.
WHERE | HAVING | |
|---|---|---|
| Evaluated | Before GROUP BY | After grouping and aggregation |
| Operates on | Individual rows | Whole groups |
| Aggregates allowed | No | Yes |
Logical order: FROM -> WHERE -> GROUP BY -> aggregates -> HAVING -> SELECT -> ORDER BY.
When WHERE runs, groups do not exist yet, so WHERE COUNT(*) > 1 is invalid. HAVING runs after aggregation and is therefore the place for conditions like COUNT(*) > 1.
Guideline: anything that can be decided from a single row (source_system = 'web', created_at >= '2024-01-01', customer_email IS NOT NULL) belongs in WHERE. Filtering early also means fewer rows get grouped, which is cheaper. Use HAVING only for conditions on aggregates.
3. Finding repeated emails
Approach
- Drop rows with no email.
- Group by
customer_email. - Count rows per group.
- Keep groups whose count exceeds 1.
SELECT
customer_email,
COUNT(*) AS duplicate_count
FROM customer_events
WHERE customer_email IS NOT NULL
GROUP BY customer_email
HAVING COUNT(*) > 1
ORDER BY duplicate_count DESC, customer_email;
Why it works
GROUP BYyields one row per distinct email.COUNT(*)is the number of occurrences of that email in the whole table.HAVING COUNT(*) > 1matches the definition of a duplicate.- The
WHEREclause shows the row-level versus group-level split from Part 2 in practice. ORDER BYis optional and only improves readability.
Complexity: O(n) time with hash aggregation (O(n log n) if the engine sorts), and O(d) space for d distinct emails.
Edge cases worth raising
- NULL emails.
GROUP BYcollapses all NULLs into one group, which would appear as a large "duplicate" if you usedCOUNT(*). A missing value is not a repeated value, so exclude NULLs withWHERE customer_email IS NOT NULL(or useCOUNT(customer_email), though the explicit filter reads more clearly). - Case and whitespace.
[email protected]and[email protected]are different strings, so exact matching will not treat them as duplicates. Since the task says "the same value," exact matching is correct, but a good candidate asks whether normalization is wanted. If so, group byLOWER(TRIM(customer_email)). - UTC timestamp. This is irrelevant here because duplicates are defined over the whole table. It would matter only if duplicates were counted per day or per window.
- Seeing the duplicate rows themselves. Use a window function such as
COUNT(*) OVER (PARTITION BY customer_email)and filter on it, orROW_NUMBER() OVER (PARTITION BY customer_email ORDER BY created_at)to keep the earliest event and flag the others for removal.
pandas equivalent
import pandas as pd
def find_duplicate_emails(df: pd.DataFrame) -> pd.DataFrame:
counts = (
df.dropna(subset=["customer_email"]) # WHERE ... IS NOT NULL
.groupby("customer_email") # GROUP BY
.size() # COUNT(*) -> Series
.rename("duplicate_count")
.reset_index() # Series -> DataFrame
)
result = counts[counts["duplicate_count"] > 1] # HAVING
return (
result.sort_values(["duplicate_count", "customer_email"],
ascending=[False, True])
.reset_index(drop=True)
)
This ties back to Part 1: groupby(...).size() produces a Series, and reset_index() converts it into a two-column DataFrame. Note that groupby drops NaN keys by default, but an explicit dropna makes the intent obvious.
Common mistakes
- Putting
COUNT(*) > 1inWHEREand being unable to explain the error. - Forgetting to handle NULLs and reporting a bogus NULL "duplicate."
- Using
SELECT *withGROUP BY, or omitting theduplicate_countalias. - Treating the UTC timestamp as relevant and adding unnecessary date logic.
- Using
DISTINCTorCOUNT(DISTINCT ...), which hides duplicates rather than surfacing them.
What a strong answer shows
Precise definitions, an explanation of evaluation order rather than a memorized rule, a correct and minimal query, and unprompted awareness of NULLs, normalization, and how to extend the solution to retrieve or remove the duplicate rows.