How to count distinct values in MySQL?


To count distinct values, you can use distinct in aggregate function count().

The syntax is as follows −

select count(distinct yourColumnName) as anyVariableName from yourTableName;

To understand the above concept, let us create a table. The following is the query to create a table −

mysql> create table DistinctDemo
   −> (
   −> Name varchar(200)
   −> );
Query OK, 0 rows affected (0.58 sec)

For our example, let us insert duplicate records in the table. The query to insert records is as follows −

mysql> insert into DistinctDemo values('John');
Query OK, 1 row affected (0.15 sec)

mysql> insert into DistinctDemo values('Sam');
Query OK, 1 row affected (0.17 sec)

mysql> insert into DistinctDemo values('John');
Query OK, 1 row affected (0.12 sec)

mysql> insert into DistinctDemo values('Johnson');
Query OK, 1 row affected (0.13 sec)

mysql> insert into DistinctDemo values('John');
Query OK, 1 row affected (0.10 sec)

mysql> insert into DistinctDemo values('Johnson');
Query OK, 1 row affected (0.12 sec)

mysql> insert into DistinctDemo values('Sam');
Query OK, 1 row affected (0.14 sec)

mysql> insert into DistinctDemo values('Johnson');
Query OK, 1 row affected (0.10 sec)

Display all records with the help of select statement. The query to display all records is as follows −

mysql> select *from DistinctDemo;

The following is the output displaying some duplicate records −

+---------+
| Name    |
+---------+
| John    |
| Sam     |
| John    |
| Johnson |
| John    |
| Johnson |
| Sam     |
| Johnson |
+---------+
8 rows in set (0.00 sec)

Here is the query that can be used to count distinct values from the table −

mysql> select count(distinct Name) as DistinctValues from DistinctDemo;

The following is the output −

+----------------+
| DistinctValues |
+----------------+
|              3 |
+----------------+
1 row in set (0.01 sec)

The result i3 tells that we have 3 distinct values in the table.

Updated on: 30-Jul-2019

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements