Duplicate Emails
Write an SQL query to report all the duplicate emails. Note that it's guaranteed that the email field is not `NULL`. Return the result table in **any order**. ### Table: Person | Column Name | Type | | :--- | :--- | | id | int | | email | varchar | `id` is the primary key column for this table. Each row contains an email address. ### Example: **Input:** ```text Person table: +----+---------+ | id | email | +----+---------+ | 1 | [email protected] | | 2 | [email protected] | | 3 | [email protected] | +----+---------+ ``` **Output:** ```text +---------+ | Email | +---------+ | [email protected] | +---------+ ```
Solve It in the BrowserPractice Explaining It Out Loud
Optimal Approach
- Time complexity: O(N log N) or O(N)
- Space complexity: O(N)
Grouping by email requires hashing or sorting rows, taking O(N) or O(N log N).
Follow-Up Questions Interviewers Ask About Duplicate Emails
- What is the difference between WHERE and HAVING in SQL?
WHERE filters rows before aggregation occurs, while HAVING filters group aggregations after the GROUP BY clause is evaluated. - Could this be solved using a self-join instead of GROUP BY?
Yes: SELECT DISTINCT p1.email FROM Person p1 JOIN Person p2 ON p1.email = p2.email AND p1.id != p2.id. However, GROUP BY with HAVING is generally more performant and idiomatic.
Practice the full problem with execution, tests, and AI code review in the interactive lab — then rehearse explaining your solution in a live voice mock interview.