Computer >> Computer tutorials >  >> Programming >> MySQL

Can I use MySQL COUNT() and DISTINCT together?


Yes, you can use COUNT() and DISTINCT together to display the count of only distinct rows. 

The syntax is as follows −

SELECT COUNT(DISTINCT yourColumnName) AS anyVariableName FROM yourTableName;

To understand the above syntax, let us create a table. 

The query to create a table is as follows −

mysql> create table CountDistinctDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> Name varchar(20),
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (3.11 sec)

Insert some records in the table using insert command. The query is as follows −

mysql> insert into CountDistinctDemo(Name) values('Carol');
Query OK, 1 row affected (0.48 sec)

mysql> insert into CountDistinctDemo(Name) values('Bob');
Query OK, 1 row affected (0.43 sec)

mysql> insert into CountDistinctDemo(Name) values('Carol');
Query OK, 1 row affected (0.26 sec)

mysql> insert into CountDistinctDemo(Name) values('John');
Query OK, 1 row affected (0.27 sec)

mysql> insert into CountDistinctDemo(Name) values('Bob');
Query OK, 1 row affected (0.35 sec)

mysql> insert into CountDistinctDemo(Name) values('Carol');
Query OK, 1 row affected (0.98 sec)

mysql> insert into CountDistinctDemo(Name) values('John');
Query OK, 1 row affected (0.26 sec)

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

mysql> insert into CountDistinctDemo(Name) values('Mike');
Query OK, 1 row affected (0.53 sec)

mysql> insert into CountDistinctDemo(Name) values('Carol');
Query OK, 1 row affected (0.31 sec)

mysql> insert into CountDistinctDemo(Name) values('David');
Query OK, 1 row affected (0.40 sec)

Display all records from the table using select statement. 

The query is as follows.

mysql> select *from CountDistinctDemo;

The following is the output.

+----+-------+
| Id | Name  |
+----+-------+
|  1 | Carol |
|  2 | Bob   |
|  3 | Carol |
|  4 | John  |
|  5 | Bob   |
|  6 | Carol |
|  7 | John  |
|  8 | Sam   |
|  9 | Mike  |
| 10 | Carol |
| 11 | David |
+----+-------+
11 rows in set (0.07 sec)

If you do not use DISTINCT, then COUNT() function gives the count of all rows. 

The query is as follows −

mysql> select count(Name) as TotalName from CountDistinctDemo;

The following is the output −

+-----------+
| TotalName |
+-----------+
|        11 |
+-----------+
1 row in set (0.04 sec)

Here is the query to use COUNT() and DISTINCT together −

mysql> SELECT COUNT(DISTINCT Name) as UniqueName FROM CountDistinctDemo;

The following is the output

+------------+
| UniqueName |
+------------+
|          6 |
+------------+
1 row in set (0.00 sec)