MySQL – Distinct Values
A column in a MySQL Table can have duplicate values based on the constraints, etc.
In this tutorial, we will learn how to get distinct values present in a specific column of a given MySQL Table.
To get unique or distinct values of a column in MySQL Table, use the following SQL Query.
</>
Copy
SELECT DISTINCT(column_name) FROM your_table_name;
You can select distinct values for one or more columns. The column names has to be separated with comma.
</>
Copy
SELECT DISTINCT column_name_1, column_name_2 FROM your_table_name;
The above query selects minimum number of rows that has unique values for each column specified in the query.
Example 1 – Get Distinct Values of a Column
In this example, we shall consider the following table data.
In the above table
- For
age
column, there are two distinct values9, 10
. - For
section
column, there are three distinct valuesA, B, C
. - For
gender
column, there are two distinct valuesM, F
.
Now, we shall write SQL Queries to get distinct values for these columns.
Get DISTINCT values for age column
</>
Copy
SELECT DISTINCT(age) FROM students;
Get DISTINCT values for section column
</>
Copy
SELECT DISTINCT section FROM students;
Get DISTINCT values for two columns
</>
Copy
SELECT DISTINCT section, age FROM students;
Conclusion
In this MySQL Tutorial, we have learnt to get distinct values of one or more columns.