MySQL query to display the count of distinct records from a column with duplicate records


Let us first create a table −

mysql> create table DemoTable
(
   StudentId int,
   StudentFirstName varchar(100)
);
Query OK, 0 rows affected (0.88 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(100,'John');
Query OK, 1 row affected (0.32 sec)
mysql> insert into DemoTable values(101,'Chris');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values(102,'John');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values(103,'Sam');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values(104,'Sam');
Query OK, 1 row affected (0.13 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-----------+------------------+
| StudentId | StudentFirstName |
+-----------+------------------+
|       100 | John             |
|       101 | Chris            |
|       102 | John             |
|       103 | Sam              |
|       104 | Sam              |
+-----------+------------------+
5 rows in set (0.00 sec)

Following is the query to display the count of distinct records from a column with duplicate records −

mysql> select count(distinct StudentFirstName) from DemoTable;

This will produce the following output −

+----------------------------------+
| count(distinct StudentFirstName) |
+----------------------------------+
|                                3 |
+----------------------------------+
1 row in set (0.00 sec)

Updated on: 26-Sep-2019

114 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements