How to speed up SELECT DISTINCT in MySQL


To speed up SELECT DISTINCT, you can create an index on the column or set of columns. Let us first create a table −

mysql> create table DemoTable
(
   Name varchar(40)
);
Query OK, 0 rows affected (1.13 sec)

Following is the query to create an index −

mysql> create index Name_Index on DemoTable(Name);
Query OK, 0 rows affected (1.56 sec)
Records: 0 Duplicates: 0 Warnings: 0

Insert some records in the table using insert command −

mysql> insert into DemoTable values('Chris');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('Mike');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('Chris');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values('Chris');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('Sam');
Query OK, 1 row affected (0.16 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-------+
| Name  |
+-------+
| Chris |
| Chris |
| Chris |
| Mike  |
| Sam   |
+-------+
5 rows in set (0.00 sec)

Following is the query for selecting only distinct records −

mysql> select distinct Name from DemoTable;

This will produce the following output −

+-------+
| Name  |
+-------+
| Chris |
| Mike  |
| Sam   |
+-------+
3 rows in set (0.02 sec)

Updated on: 01-Oct-2019

527 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements