inblog logo
|
stupefyee
    SQL문제풀기

    [SQL 문제 풀이] Delete Duplicate Emails (중복 이메일 삭제)

    Stupefyee's avatar
    Stupefyee
    Jun 05, 2025
    [SQL 문제 풀이] Delete Duplicate Emails (중복 이메일 삭제)
    Contents
    내가 작성한 쿼리
    Delete Duplicate Emails - LeetCode
    Can you solve this real interview question? Delete Duplicate Emails - Table: Person +-------------+---------+ | Column Name | Type | +-------------+---------+ | id | int | | email | varchar | +-------------+---------+ id is the primary key (column with unique values) for this table. Each row of this table contains an email. The emails will not contain uppercase letters.   Write a solution to delete all duplicate emails, keeping only one unique email with the smallest id. For SQL users, please note that you are supposed to write a DELETE statement and not a SELECT one. For Pandas users, please note that you are supposed to modify Person in place. 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 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 Duplicate Emails - LeetCode
    https://leetcode.com/problems/delete-duplicate-emails/description/
    Delete Duplicate Emails - LeetCode
    notion image
    중복된 이메일을 모두 삭제할 수 있는 솔루션을 작성하고, 가장 작은 ID를 가진 유일한 이메일 하나만 보관하세요. SQL 사용자의 경우 SELECT 문이 아닌 DELETE 문을 작성해야 한다는 점에 유의하세요. 스크립트를 실행한 후 표시되는 답은 사용자 테이블입니다. 드라이버가 먼저 코드를 컴파일하고 실행한 다음 사용자 테이블을 표시합니다. 사용자 테이블의 최종 순서는 중요하지 않습니다.
     

    내가 작성한 쿼리

    Oracle

    DELETE FROM Person WHERE id NOT IN ( SELECT MIN(id) FROM Person GROUP BY email );

    MySQL

    DELETE P1 FROM Person P1 JOIN Person P2 ON P1.email = P2.email AND P1.id > P2.id; -- 중복의 경우 둘 중에 id가 큰 것 지우기

    차이점

    • JOIN을 통한 DELETE 문법
      • MySQL: DELETE A FROM A JOIN B처럼 JOIN 사용 가능
      • Oracle: DELETE JOIN 불가능 → 서브쿼리 또는 ROWID 방식 사용 필요
        • ROWID 방식이란?
          • Oracle은 각 행에 고유한 ROWID 값을 가짐
          • ROWID는 행의 물리적 저장 위치를 나타냄
          • 중복 데이터 중 하나만 남기고 지울 때, ROWID를 활용하면 깔끔하게 처리 가능
    • 중복 조건 처리 방식
      • MySQL: P1.email = P2.email AND P1.id > P2.id로 비교하며 삭제
      • Oracle: GROUP BY email 후 MIN(id)만 남기고 나머지 삭제
    • 삭제 조건 위치
      • MySQL: JOIN 내 조건에서 중복 및 삭제 대상 지정
      • Oracle: WHERE id NOT IN (SELECT MIN(id) ...) 형태로 필터링
     
    Share article
    Contents
    내가 작성한 쿼리

    stupefyee

    RSS·Powered by Inblog