MySQL Count Distinct values process is very slow. How to fasten it?


To fasten the process, you can use INDEX. Let us first create a table −

mysql> create table DemoTable1905
   (
   FirstName varchar(20),
   LastName varchar(20) ,
   INDEX F_L_Name(FirstName,LastName)
   );
Query OK, 0 rows affected (0.00 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1905 values('John','Smith');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1905 values('John','Doe');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1905 values('Adam','Smith');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1905 values('John','Doe');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1905 values('Chris','Brown');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1905 values('Adam','Smith');
Query OK, 1 row affected (0.00 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1905;

This will produce the following output −

+-----------+----------+
| FirstName | LastName |
+-----------+----------+
| Adam      |    Smith |
| Adam      |    Smith |
| Chris     |    Brown |
| John      |      Doe |
| John      |      Doe |
| John      |    Smith |
+-----------+----------+
6 rows in set (0.00 sec)

Here is the query to count distinct values −

mysql> select count(distinct FirstName) from DemoTable1905;

This will produce the following output −

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

Updated on: 30-Dec-2019

246 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements