- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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)
Advertisements