196. Delete Duplicate Emails
Delete Duplicate Emails
Table: Person
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| id | int |
| email | varchar |
+-------------+---------+
id is the primary key column for this table.
Each row of this table contains an email. The emails will not contain uppercase letters.
Write an SQL query to delete all the duplicate emails, keeping only one unique email with the smallest id
. Note that you are supposed to write a DELETE
statement and not SELECT
one.
After running your script, the answer shown is the Person
table. The driver will first compile and run your piece of code and then show the Person
table. The final order of the Person
table does not matter.
The query result format is in the following example.
Example 1:
Input:
Person table:
+----+------------------+
| id | email |
+----+------------------+
| 1 | john@example.com |
| 2 | bob@example.com |
| 3 | john@example.com |
+----+------------------+
Output:
+----+------------------+
| id | email |
+----+------------------+
| 1 | john@example.com |
| 2 | bob@example.com |
+----+------------------+
Explanation: john@example.com is repeated two times. We keep the row with the smallest Id = 1.
DELETE p1 FROM Person p1, Person p2 WHERE p1.Email = p2.Email AND p1.Id > p2.Id;
DELETE FROM Person where id not in ( SELECT * FROM (SELECT Min(ID) from person group by email) t);
DELETE FROM PERSON WHERE ID IN (
SELECT ID FROM (SELECT ID, ROW_NUMBER() OVER (PARTITION BY EMAIL ORDER BY ID) NUM_ROW FROM PERSON) T WHERE NUM_ROW!=1)
That’s all folks! In this post, we solved LeetCode problem 196. Delete Duplicate Emails
I hope you have enjoyed this post. Feel free to share your thoughts on this.
You can find the complete source code on my GitHub repository. If you like what you learn. feel free to fork 🔪 and star ⭐ it.
In this blog, I have tried to solve leetcode questions & present the most important points to consider when improving Data structure and logic, feel free to add, edit, comment, or ask. For more information please reach me here
Happy coding!
Comments
Post a Comment