Summary: in this tutorial, you will learn about MySQL descending index and how to leverage it to increase the performance of queries.
Introduction to MySQL descending index
A descending index is an index that stores key values in the descending order. Before MySQL 8.0, you can specify the
DESC
in an index definition. However, MySQL ignored it. In the meantime, MySQL could scan the index in reverse order but it comes at a high cost.
The following statement creates a new table with an index:
When you use the
SHOW CREATE TABLE
in MySQL 5.7, you will find that the DESC
is ignored as shown below:
Starting from MySQL 8.0, the key values are stored in the descending order if you use the
DESC
keyword in the index definition. The query optimizer can take advantage of descending index when descending order is requested in the query.
The following shows the table structure in MySQL 8.0:
MySQL descending Index example
First, recreate the
t
table with four indexes in different orders:
Second, use the following stored procedure to insert rows into the
t
table:
The stored procedure inserts a number of rows (
rowCount
) with the values between low
and high
into the a
and b
columns of the t
table.
Let’s insert
10,000
rows into the t
table with the random values between 1 and 1000:
Third, query data from the
t
table with different sort orders:
Sort the values in both columns a and b in ascending order:
Here is the output:
Sort the values in the column
a
in ascending order and values in the column b
in descending order:
The output is:
Sort the values in the column
a
in descending order and values in the column b
in ascending order:
The following illustrates the output:
Sort the values in both columns
a
and b
in descending order:
The following shows the output:
In this tutorial, you have learned how to use the MySQL descending index to improve the query performance.
0 comments:
Post a Comment