Home / MySQL DBMS / MySQL DISTINCT

SQL SELECT DISTINCT statement

In MySQL the SQL SELECT DISTINCT statement is used in conjunction with the SELECT statement to remove all duplicate records and retrieve only unique records.

There can be situations when you have many duplicate records in a table. While retrieving such records, just retrieve those unique records instead of retrieving duplicate records.

Syntax

The basic syntax of the DISTINCT keyword to remove duplicate records is as follows:

SELECT DISTINCT column1, column2,.....columnN 
FROM table_name
WHERE [condition]

Example

Suppose the CUSTOMERS table has the following records:

+----+----------+-----+----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+----------+----------+
|  1 | Ha Anh |  32 | Da Nang |  2000.00 |
|  2 | Van Ha |  25 | Hanoi |  1500.00 |
|  3 | Vu Bang |  23 | Vinh |  2000.00 |
|  4 | Thu Minh |  25 | Hanoi |  6500.00 |
|  5 | Hai An |  27 | Hanoi |  8500.00 |
|  6 | Hoang |  22 | Hanoi |  4500.00 |
|  7 | Binh |  24 | Hanoi | 10000.00 |
+----+----------+-----+-----------+----------+

First, let's see how the following SELECT query returns duplicate salary records.

SELECT SALARY FROM CUSTOMERS
   ORDER BY SALARY;

This will produce the following result, where salary (2000) coming up twice is a duplicate record from the original table.

+----------+
| SALARY |
+----------+
|  1500.00 |
|  2000.00 |
|  2000.00 |
|  4500.00 |
|  6500.00 |
|  8500.00 |
| 10000.00 |
+----------+

Now use the DISTINCT keyword with the above SELECT query and then see the results

SELECT DISTINCT SALARY FROM CUSTOMERS
ORDER BY SALARY;

This will produce the following results as we have no duplicate entries.

+----------+
| SALARY |
+----------+
|  1500.00 |
|  2000.00 |
|  4500.00 |
|  6500.00 |
|  8500.00 |
| 10000.00 |
+----------+

Did you find this article helpful?

Support the author so they can write more quality articles!

Tư vấn lộ trình CNTT 🤖