Counting different distinct items in a single MySQL query?


To count items, use COUNT() along with DISTINCT. Here, DISTINCT is used to return distinct values. Let us now see an example and create a table −

mysql> create table DemoTable
(
   CustomerId int,
   CustomerName varchar(20),
   ProductName varchar(40)
);
Query OK, 0 rows affected (1.02 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(101,'Chris','Product-1');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values(102,'David','Product-2');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values(101,'Chris','Product-1');
Query OK, 1 row affected (0.30 sec)
mysql> insert into DemoTable values(101,'Chris','Product-2');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values(101,'Chris','Product-1');
Query OK, 1 row affected (0.14 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+------------+--------------+-------------+
| CustomerId | CustomerName | ProductName |
+------------+--------------+-------------+
|        101 | Chris        | Product-1   |
|        102 | David        | Product-2   |
|        101 | Chris        | Product-1   |
|        101 | Chris        | Product-2   |
|        101 | Chris        | Product-1   |
+------------+--------------+-------------+
5 rows in set (0.00 sec)

Following is the query to count different items in a single query −

mysql> select count(distinct ProductName) from DemoTable where CustomerId=101;

This will produce the following output −

+-----------------------------+
| count(distinct ProductName) |
+-----------------------------+
|                           2 |
+-----------------------------+
1 row in set (0.00 sec)

Updated on: 07-Oct-2019

78 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements