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:

  1. pandas tabular abstractions: Contrast a pandas Series against a pandas DataFrame, and describe one concrete situation suited to each object.
  2. SQL filtering stages: Explain how row filtering with WHERE differs from group filtering with HAVING, including the point in query evaluation where each runs.
  3. Graded SQL task — repeated customer emails: Given an event ingestion table customer_events (where created_at timestamps are recorded in UTC), write a SQL query that surfaces every repeated customer_email across 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_email may be NULL; NULL entries must never appear in the output even when multiple rows contain NULL.
  • String comparison is exact (case-sensitive, without trimming whitespace).
  • duplicate_count equals the full count of rows matching that customer_email across all source_system values.

Step-by-step walkthrough

  1. Overview of the three-part question

    This technical screen checks three everyday Data Engineering fundamentals in sequence:

    1. pandas data structures: when to work with a 1D Series versus a 2D DataFrame.
    2. SQL filtering phases: why WHERE and HAVING exist separately and when to use each.
    3. Practical SQL data-quality check: finding duplicate customer_email values in customer_events and returning (customer_email, duplicate_count).

    Only Task 3 (the SQL query) is graded by the test runner, and Task 2 (WHERE vs HAVING) is the exact building block needed to write Task 3 cleanly. Let's walk through all three parts from first principles.

  2. Part 1: pandas Series vs DataFrame

    Think of a spreadsheet:

    • A Series is one-dimensional: a single column of values sharing one data type (dtype), paired with a row Index (the row labels).
    • A DataFrame is two-dimensional: a full table made up of named columns that all share the same row Index. Under the hood, each column of a DataFrame is a Series with its own dtype (for example, int64 for IDs and string for 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   | support
    

    When to use each in practice:

    • Use a Series when operating on a single variable in isolation — for example, calling events["customer_email"].value_counts() to count how often each email occurs, or computing a rolling average on a daily revenue time series.
    • Use a DataFrame when working with multi-field records — for example, loading an ingestion table, filtering events by source_system, joining events to a customers table, 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]
    
  3. Part 2: SQL WHERE vs HAVING

    To understand WHERE versus HAVING, 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 output
    

    Because of this timeline:

    • WHERE filters individual rows before GROUP BY runs. It looks at one row at a time, so aggregate functions like COUNT(*) or SUM(...) do not exist yet — writing WHERE COUNT(*) > 1 raises an immediate error (misuse of aggregate: COUNT()). Filtering early in WHERE also shrinks the number of rows the engine has to group.
    • HAVING filters aggregated groups after GROUP BY has bundled rows together and calculated their totals. Any condition on COUNT(...), SUM(...), AVG(...), MIN(...), or MAX(...) belongs in HAVING.
    -- 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 counting
    
  4. Part 3: Exclude NULL emails and group by email

    Now let's build the graded query on customer_events. Three details matter for correctness:

    1. Exact value match: 'Ann@x.com' and 'ann@x.com' are distinct string values unless the prompt asks to normalize case.
    2. Total row count: if an email appears on 3 rows, duplicate_count is 3 (total rows), not 2 (extra copies).
    3. NULL is not an email: in SQL, NULL represents a missing or unknown value. However, GROUP BY places all NULL values into a single bucket! If two rows had customer_email = NULL and we forgot to filter them out, that bucket would have COUNT(*) = 2 and falsely show up as a "duplicate" email.

    Because checking whether customer_email is missing inspects one row at a time, we filter it out up front in WHERE. Remember that in SQL, customer_email != NULL evaluates to UNKNOWN (never TRUE), so always write IS 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
    
  5. Keep only repeated emails with HAVING

    Once GROUP BY customer_email has formed one bucket per non-NULL email and COUNT(*) has counted the rows in each bucket, we keep only the buckets with at least two rows using HAVING:

    -- Keep only email groups that appear on 2 or more rows
    HAVING COUNT(*) > 1
    
  6. Trace 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.io arrived from three different source_system values (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).

  7. 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-NULL emails 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 NULL emails: Filtered out by WHERE 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_count accurately reports 4.
  • No duplicates or empty table: Returns zero rows while keeping the columns customer_email and duplicate_count.
  • Empty string '': Unlike NULL, '' is an actual string value; if upstream pipelines represent missing emails as '', exclude it too with WHERE customer_email IS NOT NULL AND customer_email <> ''.

Common mistakes

  • Putting COUNT(*) > 1 inside WHERE: Aggregate functions cannot appear in WHERE because grouping has not happened yet; always filter group counts in HAVING.
  • Writing WHERE customer_email != NULL: SQL uses three-valued logic (TRUE, FALSE, UNKNOWN), where any = or != comparison against NULL yields UNKNOWN and filters out every row in the table! Always use IS NOT NULL.
  • Forgetting WHERE customer_email IS NOT NULL: Causes two or more missing-email rows to collapse into one NULL group 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): Inside GROUP BY customer_email, every group has only 1 distinct email, so COUNT(DISTINCT customer_email) > 1 is 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) without WHERE: Because COUNT(column_name) ignores NULL values (unlike COUNT(*), which counts rows), the NULL group evaluates to COUNT(customer_email) = 0 and gets dropped by HAVING COUNT(customer_email) > 1. Writing WHERE customer_email IS NOT NULL explicitly is still preferred because it makes your NULL rule self-documenting and lets the engine skip NULL rows before grouping.
  • Equivalent in pandas: counts = df["customer_email"].value_counts() followed by counts[counts > 1]. Because Series.value_counts() defaults to dropna=True, missing NaN/None emails 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 BY collapses 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, compute COUNT(*) OVER (PARTITION BY customer_email) AS email_cnt in a subquery and filter WHERE email_cnt > 1. To deduplicate and keep only the earliest row per email, number each email's rows chronologically with ROW_NUMBER() (adding event_id as a deterministic tie-breaker) and keep rn = 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, store normalized_email as a dedicated cleaned column (or build a functional index on LOWER(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)], where keep=False marks every occurrence of a repeated email as True. Watch out for a subtle trap: unlike value_counts(), DataFrame.duplicated() treats two NaN/None values as duplicates of each other! Always filter out missing emails first with df.dropna(subset=["customer_email"]) before calling .duplicated().

Follow-up questions

Similar questions

More Rbcroyalbank interview questions

All 5 Rbcroyalbank questions →