How can I count unique records from a column in MySQL database?


For this, use aggregate function count(*) to count to GROUP BY to group. Let us first create a table −

mysql> create table DemoTable
(
   UserName varchar(100),
   UserPostMessage text
);
Query OK, 0 rows affected (0.54 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('Chris','Hi');
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable values('David','Hello');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values('Chris','Awesome');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values('Chris','Amazing');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values('David','Nice Place');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values('Chris','Amazing');
Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----------+-----------------+
| UserName | UserPostMessage |
+----------+-----------------+
| Chris    | Hi              |
| David    | Hello           |
| Chris    | Awesome         |
| Chris    | Amazing         |
| David    | Nice Place      |
| Chris    | Amazing         |
+----------+-----------------+
6 rows in set (0.00 sec)

Here is the query to count unique records from a column in my MySQL database −

mysql> select UserName,count(DISTINCT UserPostMessage) AS NumberOfMessagesPostByUser from DemoTable group by UserName;

This will produce the following output −

+----------+----------------------------+
| UserName | NumberOfMessagesPostByUser |
+----------+----------------------------+
| Chris    |                          3 |
| David    |                          2 |
+----------+----------------------------+
2 rows in set (0.00 sec)

Updated on: 27-Sep-2019

97 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements