Search code examples
sqloracleduplicatessql-delete

How to delete the rows with three same data columns and one different data column


I have a table "MARK_TABLE" as below.

How can I delete the rows with same "STUDENT", "COURSE" and "SCORE" values?

| ID | STUDENT | COURSE | SCORE |
|----|---------|--------|-------|
| 1  |    1    |    1   |  60   |
| 3  |    1    |    2   |  81   |
| 4  |    1    |    3   |  81   |
| 9  |    2    |    1   |  80   |
| 10 |    1    |    1   |  60   |
| 11 |    2    |    1   |  80   |

Now I already filtered the data I want to KEEP, but without the "ID"...

SELECT student, course, score FROM mark_table
INTERSECT
SELECT student, course, score FROM mark_table

The output:

| STUDENT | COURSE | SCORE |
|---------|--------|-------|
|    1    |    1   |  60   |
|    1    |    2   |  81   |
|    1    |    3   |  81   |
|    2    |    1   |  80   |

Solution

  • Use the following query to delete the desired rows:

    DELETE FROM MARK_TABLE M
    WHERE
        EXISTS (
            SELECT
                1
            FROM
                MARK_TABLE M_IN
            WHERE
                M.STUDENT = M_IN.STUDENT
                AND M.COURSE = M_IN.COURSE
                AND M.SCORE = M_IN.SCORE
                AND M.ID < M_IN.ID
        )
    

    OUTPUT

    enter image description here

    db<>fiddle demo

    Cheers!!