You need to use GROUP BY for this. Let us first create a table −
mysql> create table DemoTable ( StudentFirstName varchar(20) ); Query OK, 0 rows affected (0.74 sec)
Insert records in the table using insert command −
mysql> insert into DemoTable values('John');
Query OK, 1 row affected (1.34 sec)
mysql> insert into DemoTable values('Carol');
Query OK, 1 row affected (0.28 sec)
mysql> insert into DemoTable values('John');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('John');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('Bob');
Query OK, 1 row affected (0.25 sec)
mysql> insert into DemoTable values('David');
Query OK, 1 row affected (0.55 sec)
mysql> insert into DemoTable values('Bob');
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable values('Carol');
Query OK, 1 row affected (0.37 sec)
mysql> insert into DemoTable values('Robert');
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 −
+------------------+ | StudentFirstName | +------------------+ | John | | Carol | | John | | John | | Bob | | David | | Bob | | Carol | | Robert | +------------------+ 9 rows in set (0.00 sec)
Here is the query to count the distinct column in MySQL −
mysql> select StudentFirstName,count(*) from DemoTable group by StudentFirstName;
This will produce the following output −
+------------------+----------+ | StudentFirstName | count(*) | +------------------+----------+ | John | 3 | | Carol | 2 | | Bob | 2 | | David | 1 | | Robert | 1 | +------------------+----------+ 5 rows in set (0.00 sec)