English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Can DISTINCT and COUNT be used together in MySQL queries?

We can use DISTINCT and COUNT together in a MySQL query. First, let's create a table. The CREATE command is used to create a table.

mysql> create table DistCountDemo
   - > (
   - > id int,
   - > name varchar(100),
   - > age int
   - > );

Insert records with the help of the INSERT command.

mysql> insert into DistCountDemo values(1,'John',23);
mysql> insert into DistCountDemo values(2,'Bob',24);
mysql> insert into DistCountDemo values(3,'John',23);
mysql> insert into DistCountDemo values(4,'Carol',23);

Display all records with the help of the SELECT statement.

mysql> select *FROM DistCountDemo;

The following is the output.

+------+-------+------+
| id | name | age |
+------+-------+------+
|    1 | John |   23 |
|    2 | Bob |   24 |
|    3 | John |   23 |
|    4 | Carol |   23 |
+------+-------+------+
4 rows in set (0.00 sec)

Use COUNT and DISTINCT to find23number of students of that age.

mysql> SELECT COUNT(DISTINCT name) FROM DistCountDemo WHERE age=23;

The following is the output.

+----------------------+
| COUNT(DISTINCT name) |
+----------------------+
|                    2 |
+----------------------+
1 row in set (0.05 sec)