MySQL query to get the count of distinct records in a column

MySQLMySQLi Database

To get the count of distinct records, use DISTINCT along with COUNT(). Following is the syntax −

select count(DISTINCT yourColumnName) from yourTableName;

Let us first create a table −

mysql> create table DemoTable
-> (
-> Name varchar(20),
-> Score int
-> );
Query OK, 0 rows affected (0.67 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('John',56);
Query OK, 1 row affected (0.18 sec)

mysql> insert into DemoTable values('Sam',89);
Query OK, 1 row affected (0.20 sec)

mysql> insert into DemoTable values('John',56);
Query OK, 1 row affected (0.17 sec)

mysql> insert into DemoTable values('Carol',60);
Query OK, 1 row affected (0.20 sec)

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

mysql> insert into DemoTable values('Carol',60);
Query OK, 1 row affected (0.20 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable

Output

This will produce the following output −

+-------+-------+
| Name  | Score |
+-------+-------+
| John  | 56    |
| Sam   | 89    |
| John  | 56    |
| Carol | 60    |
| Sam   | 89    |
| Carol | 60    |
+-------+-------+
6 rows in set (0.00 sec)

Here is the query to get to get the count of distinct records in a column −

mysql> select count(DISTINCT Score) from DemoTable;

Output

This will produce the following output −

+-----------------------+
| count(DISTINCT Score) |
+-----------------------+
| 3                     |
+-----------------------+
1 row in set (0.00 sec)
raja
Published on 10-Jul-2019 13:28:36
Advertisements