Pandas Structures, SQL Filtering, and Duplicate Emails
Easy · Data Manipulation (SQL/Python) · Data Engineer · Technical Screen
Problem Statement
A junior data-engineering technical screen combines two foundational concept prompts with a hands-on SQL data-quality query:
- pandas tabular abstractions: Contrast a pandas
Seriesagainst a pandasDataFrame, and describe one concrete situation suited to each object. - SQL filtering stages: Explain how row filtering with
WHEREdiffers from group filtering withHAVING, including the point in query evaluation where each runs. - Graded SQL task — repeated customer emails: Given an event ingestion table
customer_events(wherecreated_attimestamps are recorded in UTC), write a SQL query that surfaces every repeatedcustomer_emailacross the entire table.
For the graded SQL query, an email counts as repeated whenever the exact same non-NULL customer_email string occurs on at least two rows in customer_events (across all source_system values combined). Return two columns:
customer_email— the repeated email string.duplicate_count— the total row count carrying that exact email (counting all occurrences, not just extra copies).
Omit emails that occur only once as well as rows where customer_email is NULL. Result rows may appear in any order.
Input Schema
customer_events
| Column | Type | Description |
|---|---|---|
event_id |
BIGINT |
Identifier of the ingested event record |
customer_email |
VARCHAR |
Contact email on the event (nullable when missing) |
source_system |
VARCHAR |
Upstream producer name (such as 'checkout', 'ios', or 'support') |
created_at |
TIMESTAMP |
UTC timestamp when the event was recorded |
Examples
Example 1
Input (customer_events):
| event_id | customer_email | source_system | created_at |
|---|---|---|---|
| 101 | maya@acme.io | checkout | 2025-03-10 08:15:00 |
| 102 | liam@acme.io | ios | 2025-03-10 09:00:00 |
| 103 | maya@acme.io | support | 2025-03-10 14:20:00 |
| 104 | noah@acme.io | checkout | 2025-03-11 11:05:00 |
| 105 | liam@acme.io | checkout | 2025-03-11 16:40:00 |
| 106 | maya@acme.io | ios | 2025-03-12 07:50:00 |
| 107 | priya@acme.io | support | 2025-03-12 13:10:00 |
Output:
| customer_email | duplicate_count |
|---|---|
| liam@acme.io | 2 |
| maya@acme.io | 3 |
Walk-through:
- 'maya@acme.io' appears on events 101, 103, and 106 across three channels (3 rows total).
- 'liam@acme.io' appears on events 102 and 105 (2 rows total).
- 'noah@acme.io' and 'priya@acme.io' each occur once and are excluded.
Example 2
Input (customer_events):
| event_id | customer_email | source_system | created_at |
|---|---|---|---|
| 201 | NULL | ios | 2025-04-01 10:00:00 |
| 202 | NULL | checkout | 2025-04-01 10:05:00 |
| 203 | chen@acme.io | ios | 2025-04-01 11:00:00 |
| 204 | Chen@acme.io | support | 2025-04-01 11:30:00 |
| 205 | chen@acme.io | checkout | 2025-04-01 12:00:00 |
Output:
| customer_email | duplicate_count |
|---|---|
| chen@acme.io | 2 |
Walk-through:
- Missing NULL emails on events 201 and 202 represent absent values rather than a shared address, so they are ignored.
- Exact string matching treats 'chen@acme.io' (2 rows) as distinct from 'Chen@acme.io' (1 row).
Constraints
- Only the SQL query in Task 3 is executed by the automated test suite; Tasks 1 and 2 are conceptual discussion prompts covered in the walkthrough.
customer_emailmay beNULL;NULLentries must never appear in the output even when multiple rows containNULL.- String comparison is exact (case-sensitive, without trimming whitespace).
duplicate_countequals the full count of rows matching thatcustomer_emailacross allsource_systemvalues.
Step-by-step walkthrough
Overview of the three-part question
This technical screen checks three everyday Data Engineering fundamentals in sequence:
- pandas data structures: when to work with a 1D
Seriesversus a 2DDataFrame. - SQL filtering phases: why
WHEREandHAVINGexist separately and when to use each. - Practical SQL data-quality check: finding duplicate
customer_emailvalues incustomer_eventsand returning(customer_email, duplicate_count).
Only Task 3 (the SQL query) is graded by the test runner, and Task 2 (
WHEREvsHAVING) is the exact building block needed to write Task 3 cleanly. Let's walk through all three parts from first principles.- pandas data structures: when to work with a 1D
Part 1: pandas Series vs DataFrame
Think of a spreadsheet:
- A
Seriesis one-dimensional: a single column of values sharing one data type (dtype), paired with a rowIndex(the row labels). - A
DataFrameis two-dimensional: a full table made up of named columns that all share the same rowIndex. Under the hood, each column of aDataFrameis aSerieswith its owndtype(for example,int64for IDs andstringfor emails).
Series (1D: one column + index) DataFrame (2D: multiple named columns + shared index) idx | customer_email idx | event_id | customer_email | source_system ----+--------------- ----+----------+----------------+-------------- 0 | maya@acme.io 0 | 101 | maya@acme.io | checkout 1 | liam@acme.io 1 | 102 | liam@acme.io | ios 2 | maya@acme.io 2 | 103 | maya@acme.io | supportWhen to use each in practice:
- Use a
Serieswhen operating on a single variable in isolation — for example, callingevents["customer_email"].value_counts()to count how often each email occurs, or computing a rolling average on a daily revenue time series. - Use a
DataFramewhen working with multi-field records — for example, loading an ingestion table, filtering events bysource_system, joining events to acustomerstable, or grouping by multiple columns.
import pandas as pd events = pd.DataFrame({ "event_id": [101, 102, 103], "customer_email": ["maya@acme.io", "liam@acme.io", "maya@acme.io"], "source_system": ["checkout", "ios", "support"], }) # Single bracket -> 1D Series (one column) emails = events["customer_email"] # Double bracket (list of column names) -> 2D DataFrame (a sub-table) subset = events[["customer_email", "source_system"]] # Count frequencies on the Series (NaN missing values are ignored by default) email_counts = emails.value_counts() duplicates = email_counts[email_counts > 1]- A
Part 2: SQL WHERE vs HAVING
To understand
WHEREversusHAVING, follow the logical order in which a database engine evaluates a grouped SQL query:1. FROM --> read the input table 2. WHERE --> filter individual rows (before any grouping happens) 3. GROUP BY --> bucket the surviving rows into groups 4. HAVING --> filter whole groups (after group aggregates are computed) 5. SELECT --> project the output columns 6. ORDER BY --> sort the final outputBecause of this timeline:
WHEREfilters individual rows beforeGROUP BYruns. It looks at one row at a time, so aggregate functions likeCOUNT(*)orSUM(...)do not exist yet — writingWHERE COUNT(*) > 1raises an immediate error (misuse of aggregate: COUNT()). Filtering early inWHEREalso shrinks the number of rows the engine has to group.HAVINGfilters aggregated groups afterGROUP BYhas bundled rows together and calculated their totals. Any condition onCOUNT(...),SUM(...),AVG(...),MIN(...), orMAX(...)belongs inHAVING.
-- Example combining both: emails appearing more than once among 'checkout' events SELECT customer_email, COUNT(*) AS checkout_event_count FROM customer_events WHERE source_system = 'checkout' -- row-level filter: runs BEFORE grouping GROUP BY customer_email HAVING COUNT(*) > 1 -- group-level filter: runs AFTER countingPart 3: Exclude NULL emails and group by email
Now let's build the graded query on
customer_events. Three details matter for correctness:- Exact value match:
'Ann@x.com'and'ann@x.com'are distinct string values unless the prompt asks to normalize case. - Total row count: if an email appears on 3 rows,
duplicate_countis3(total rows), not2(extra copies). NULLis not an email: in SQL,NULLrepresents a missing or unknown value. However,GROUP BYplaces allNULLvalues into a single bucket! If two rows hadcustomer_email = NULLand we forgot to filter them out, that bucket would haveCOUNT(*) = 2and falsely show up as a "duplicate" email.
Because checking whether
customer_emailis missing inspects one row at a time, we filter it out up front inWHERE. Remember that in SQL,customer_email != NULLevaluates toUNKNOWN(neverTRUE), so always writeIS NOT NULL:SELECT customer_email, -- Count total rows carrying this exact email (including its first occurrence) COUNT(*) AS duplicate_count FROM customer_events -- Exclude missing emails before grouping so multiple NULL rows are not reported as a duplicate WHERE customer_email IS NOT NULL GROUP BY customer_email- Exact value match:
Keep only repeated emails with HAVING
Once
GROUP BY customer_emailhas formed one bucket per non-NULLemail andCOUNT(*)has counted the rows in each bucket, we keep only the buckets with at least two rows usingHAVING:-- Keep only email groups that appear on 2 or more rows HAVING COUNT(*) > 1Trace on Example 1
Let's trace all 7 rows of Example 1 through
WHERE->GROUP BY->HAVING:customer_email | event_ids | source_systems | COUNT(*) | HAVING COUNT(*) > 1? ---------------+---------------+-------------------------+----------+--------------------- maya@acme.io | 101, 103, 106 | checkout, support, ios | 3 | KEEP (3 > 1) liam@acme.io | 102, 105 | ios, checkout | 2 | KEEP (2 > 1) noah@acme.io | 104 | checkout | 1 | drop (1 is not > 1) priya@acme.io | 107 | support | 1 | drop (1 is not > 1)Notice that
maya@acme.ioarrived from three differentsource_systemvalues (checkout,support,ios), and all three count together because repeated emails are checked across the entire table. The final output has two rows:('liam@acme.io', 2)and('maya@acme.io', 3).Complete SQL query
Here is the complete SQL query for Task 3:
SELECT customer_email, -- Count total rows carrying this exact email (including its first occurrence) COUNT(*) AS duplicate_count FROM customer_events -- Exclude missing emails before grouping so multiple NULL rows are not reported as a duplicate WHERE customer_email IS NOT NULL GROUP BY customer_email -- Keep only email groups that appear on 2 or more rows HAVING COUNT(*) > 1✅ Submit now — all tests should pass.
Intuition & how it works
Imagine sorting paper customer event slips into labeled mail slots — one slot per email address — while setting aside any slip whose email line is blank (NULL). Once every slip with an email has been dropped into its matching slot, finding duplicate emails simply means walking past the slots and recording every slot that holds two or more slips, along with how many slips sit inside it.
Beginners run into two common traps when translating this into SQL. First, writing WHERE COUNT(*) > 1 fails immediately because WHERE inspects one row at a time before any slips have been grouped or counted. Second, skipping WHERE customer_email IS NOT NULL backfires when two or more rows are missing an email: SQL's GROUP BY puts all NULL values into a single bucket, so two blank emails would get COUNT(*) = 2 and be falsely reported as (NULL, 2).
Let's trace a tiny 5-row example with emails 'maya@acme.io', NULL, 'maya@acme.io', NULL, and 'noah@acme.io':
1. WHERE customer_email IS NOT NULL filters rows one by one, discarding both NULL rows and passing 'maya@acme.io', 'maya@acme.io', 'noah@acme.io' forward.
2. GROUP BY customer_email with COUNT(*) forms one bucket per distinct email and counts its rows: 'maya@acme.io' -> 2 and 'noah@acme.io' -> 1.
3. HAVING COUNT(*) > 1 filters the finished buckets, dropping 'noah@acme.io' (1) and returning ('maya@acme.io', 2).
Complexity
Let N be the total number of rows in customer_events and E be the number of distinct non-NULL emails (E <= N).
- Time: O(N) using a hash aggregate (an in-memory hash table mapping each email to its running count in a single pass), or O(N log N) when the database engine sorts the N non-
NULLemails first so identical emails sit side by side (SQLite's default plan without an index). - Space: O(E) memory for a hash aggregate (one counter per distinct email), or O(N) temporary space if the engine sorts all N rows in a temporary B-tree.
Index that helps in production:
- Creating an index on customer_events(customer_email) acts as a covering index (an index containing every column the query touches, so the table heap is never read) and stores non-NULL emails already in sorted order. The engine can jump straight past NULL entries and stream through each email group sequentially in O(N) time and O(1) extra working memory beyond the output rows.
Edge cases
- Multiple
NULLemails: Filtered out byWHERE customer_email IS NOT NULL, so missing values never form a fake(NULL, k)duplicate row. - Case sensitivity and trailing spaces: By default, SQLite compares strings byte-for-byte, so
'Ann@x.com','ann@x.com', and'ann@x.com 'are treated as three different exact values. - Completely identical duplicate rows:
COUNT(*)counts every physical row in the group, so if an ingestion retry inserts the exact same row twice (and the email appears on 2 other rows),duplicate_countaccurately reports4. - No duplicates or empty table: Returns zero rows while keeping the columns
customer_emailandduplicate_count. - Empty string
'': UnlikeNULL,''is an actual string value; if upstream pipelines represent missing emails as'', exclude it too withWHERE customer_email IS NOT NULL AND customer_email <> ''.
Common mistakes
- Putting
COUNT(*) > 1insideWHERE: Aggregate functions cannot appear inWHEREbecause grouping has not happened yet; always filter group counts inHAVING. - Writing
WHERE customer_email != NULL: SQL uses three-valued logic (TRUE,FALSE,UNKNOWN), where any=or!=comparison againstNULLyieldsUNKNOWNand filters out every row in the table! Always useIS NOT NULL. - Forgetting
WHERE customer_email IS NOT NULL: Causes two or more missing-email rows to collapse into oneNULLgroup and appear in the output. - Returning
COUNT(*) - 1: Computes the number of extra copies rather than the total occurrences requested by the problem. - Using
COUNT(DISTINCT customer_email): InsideGROUP BY customer_email, every group has only 1 distinct email, soCOUNT(DISTINCT customer_email) > 1is always false and returns nothing. - Grouping by
(customer_email, source_system): Only detects duplicates within the same source system and misses an email like'maya@acme.io'that appears once in'checkout', once in'support', and once in'ios'.
Alternative approaches
- Using
COUNT(customer_email)withoutWHERE: BecauseCOUNT(column_name)ignoresNULLvalues (unlikeCOUNT(*), which counts rows), theNULLgroup evaluates toCOUNT(customer_email) = 0and gets dropped byHAVING COUNT(customer_email) > 1. WritingWHERE customer_email IS NOT NULLexplicitly is still preferred because it makes yourNULLrule self-documenting and lets the engine skipNULLrows before grouping. - Equivalent in pandas:
counts = df["customer_email"].value_counts()followed bycounts[counts > 1]. BecauseSeries.value_counts()defaults todropna=True, missingNaN/Noneemails are excluded automatically.
Follow-up questions
- How would you retrieve every full event row tied to a repeated email, or deduplicate the table down to each email's earliest event? Because
GROUP BYcollapses multiple events into a single summary row, both tasks call for a window function (which computes per-group values while keeping every individual row). To list all duplicate event rows, computeCOUNT(*) OVER (PARTITION BY customer_email) AS email_cntin a subquery and filterWHERE email_cnt > 1. To deduplicate and keep only the earliest row per email, number each email's rows chronologically withROW_NUMBER()(addingevent_idas a deterministic tie-breaker) and keeprn = 1:
sql
WITH ranked AS (
SELECT
event_id,
customer_email,
source_system,
created_at,
ROW_NUMBER() OVER (
PARTITION BY customer_email
ORDER BY created_at ASC, event_id ASC
) AS rn
FROM customer_events
WHERE customer_email IS NOT NULL
)
SELECT event_id, customer_email, source_system, created_at
FROM ranked
WHERE rn = 1
- How should the query change if letter-case differences and leading or trailing spaces (such as 'Maya@Acme.io' vs ' maya@acme.io ') represent the same person? Normalize both whitespace and letter case by grouping and selecting
LOWER(TRIM(customer_email)) AS normalized_email. In a production data pipeline, storenormalized_emailas a dedicated cleaned column (or build a functional index onLOWER(TRIM(customer_email))) so every downstream query shares the exact same deduplication rule and can still use an index without re-computing string functions on every scan. - How would you flag all duplicate-email rows in pandas, and how does DataFrame.duplicated() behave on missing values? You can filter full rows using
df[df.duplicated(subset=["customer_email"], keep=False)], wherekeep=Falsemarks every occurrence of a repeated email asTrue. Watch out for a subtle trap: unlikevalue_counts(),DataFrame.duplicated()treats twoNaN/Nonevalues as duplicates of each other! Always filter out missing emails first withdf.dropna(subset=["customer_email"])before calling.duplicated().
Follow-up questions
- How would you retrieve every full event row tied to a repeated email, or deduplicate the table down to each email's earliest event?
- How should the query change if letter-case differences and leading or trailing spaces (such as 'Maya@Acme.io' vs ' maya@acme.io ') represent the same person?
- How would you flag all duplicate-email rows in pandas, and how does DataFrame.duplicated() behave on missing values?
Similar questions
- Data Engineering Intern Screen: Graduate Skills, ETL Contracts, and Debugging
- Schema Contracts, End-to-End Pipeline Quality, and Production Troubleshooting
- Technical Pushback, Skill Gaps, and Pairing Decisions
- In-Memory Key-Value Command Processor
- Job Posting Engagement Metrics Excluding Non-Viewing Applicants
- Compute 7-Day DAU, D1 Retention, and Revenue Cohorts