
- Learn MySQL
- MySQL - Home
- MySQL - Introduction
- MySQL - Installation
- MySQL - Administration
- MySQL - PHP Syntax
- MySQL - Connection
- MySQL - Create Database
- MySQL - Drop Database
- MySQL - Select Database
- MySQL - Data Types
- MySQL - Create Tables
- MySQL - Drop Tables
- MySQL - Insert Query
- MySQL - Select Query
- MySQL - Where Clause
- MySQL - Update Query
- MySQL - Delete Query
- MySQL - Like Clause
- MySQL - Sorting Results
- MySQL - Using Join
- MySQL - NULL Values
- MySQL - Regexps
- MySQL - Transactions
- MySQL - Alter Command
- MySQL - Indexes
- MySQL - Temporary Tables
- MySQL - Clone Tables
- MySQL - Database Info
- MySQL - Using Sequences
- MySQL - Handling Duplicates
- MySQL - SQL Injection
- MySQL - Database Export
- MySQL - Database Import
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)
- Related Articles
- MySQL SELECT DISTINCT and count?
- MySQL select * with distinct id?
- How to select distinct value from one MySQL column only?
- SELECT DISTINCT vs GROUP BY in MySQL?
- MySQL query to select distinct order by id
- Select distinct values from two columns in MySQL?
- Randomly SELECT distinct rows in a MySQL table?
- Select distinct combinations from two columns in MySQL?
- MYSQL select DISTINCT values from two columns?
- MySQL Select Statement DISTINCT for Multiple Columns?
- How to select all distinct filename extensions from a table of filenames in MySQL?
- MySQL query to select average from distinct column of table?
- How to speed up $group phase in aggregation?
- MySQL select distinct dates from datetime column in a table?
- Explain the use of SELECT DISTINCT statement in MySQL using Python?

Advertisements