Guide to Using Invisible Indexes and Descending Indexes in MySQL 8

MySQL tutorial - IT technology blog
MySQL tutorial - IT technology blog

1. Quick Start (Apply in 5 Minutes)

Managing MySQL 8 databases often involves two persistent challenges: safely validating unused indexes before permanently dropping them, and completely eliminating Using filesort when sorting queries across mixed directions. Here is the ready-to-use syntax for each scenario:

Temporarily Hide an Index for Safe Testing (Invisible Index)

-- Hide index from the Query Optimizer
ALTER TABLE orders ALTER INDEX idx_created_at INVISIBLE;

-- Instantly restore in 0.01s if queries slow down
ALTER TABLE orders ALTER INDEX idx_created_at VISIBLE;

Create an Index Optimized for Multi-Directional Sorting (Descending Index)

-- Optimized for queries filtering status, grouping department ascending, and sorting salary descending
CREATE INDEX idx_dept_salary ON employees (department_id ASC, salary DESC);

These two techniques allow teams to clean up schemas confidently without downtime while entirely eliminating the overhead of disk-based sorting.

2. Technical Deep Dive

Invisible Indexes: Dropping Indexes in Production Without the Heart Attack

Prior to MySQL 8.0, cleaning up redundant indexes on tables with tens of millions of rows was always a gamble. You might run DROP INDEX, only to discover hours later that a nightly cron job depended on it, sending CPU usage spiking to 100% due to full table scans.

Recovering from such mistakes was painful. Running ADD INDEX on a 50GB table could take anywhere from 30 minutes to several hours, heavily loading the system and causing replication lag to soar.

Invisible Indexes in MySQL 8.0 solve this problem permanently:

  • Ignored by the Optimizer: The Query Planner acts as if the index does not exist when generating Execution Plans for SELECT statements.
  • Maintained by InnoDB: All INSERT, UPDATE, and DELETE operations continue to maintain the underlying B-Tree structure, keeping index data fully up-to-date.
  • Instant State Toggling: Switching between VISIBLE and INVISIBLE only modifies metadata in the data dictionary. The operation completes in under 10ms without rebuilding the B-Tree.

Descending Indexes: The Lifesaver for Multi-Directional Sorting

In MySQL 5.7, specifying DESC in an index definition was syntactically valid, but the parser simply accepted and ignored it. InnoDB always stored B-Tree entries in ascending order (ASC).

When sorting by a single column (such as ORDER BY created_at DESC), MySQL 5.7 could still cope by performing an index backward scan, although it ran about 10-15% slower than a forward scan.

The bottleneck occurred when sorting across multiple columns with conflicting directions—for example, ORDER BY category_id ASC, price DESC. Backward scanning cannot handle mixed directions. As a result, the Optimizer was forced to load the full result set into memory or write temporary files to disk, triggering Using filesort.

MySQL 8.0 eliminates this limitation by storing leaf page nodes directly in descending order. The engine simply scans the index sequentially from left to right to produce the correctly sorted output, consuming zero extra CPU cycles for sorting.

3. Hands-on Testing and Benchmarks

Enabling Invisible Indexes for a Debug Session

Suppose you created a test index and want to evaluate its execution plan without exposing production traffic to potential regressions. Create the index as INVISIBLE, then enable invisible index usage exclusively within your debug session:

-- Create an invisible index; live user traffic remains unaffected
CREATE INDEX idx_user_status_exp ON users (status, expired_at) INVISIBLE;

-- Force the Optimizer to evaluate invisible indexes only in this session
SET SESSION optimizer_switch = 'use_invisible_indexes=on';

-- Inspect the actual Execution Plan
EXPLAIN ANALYZE SELECT id, username FROM users WHERE status = 'ACTIVE' AND expired_at < NOW();

-- Reset session settings back to default after benchmarking
SET SESSION optimizer_switch = 'use_invisible_indexes=off';

This approach allows you to benchmark performance with confidence without disrupting query execution across the rest of the application.

Eliminating Using filesort with Composite Descending Indexes

Consider a real-world scenario on an orders table containing 5 million rows. The application needs to retrieve paid orders grouped by customer and ordered by the newest records first:

SELECT order_id, customer_id, total_amount, created_at 
FROM orders 
WHERE status = 'PAID' 
ORDER BY customer_id ASC, created_at DESC 
LIMIT 20;

If you create a standard index where all columns default to ASC:

CREATE INDEX idx_status_cust_created_asc ON orders (status, customer_id ASC, created_at ASC);

Inspecting with EXPLAIN reveals that MySQL falls back to filesort:

-> Limit: 20 row(s)
    -> Sort: orders.customer_id, orders.created_at DESC, limit input to 20 row(s)
        -> Filter: (orders.`status` = 'PAID')  (Using filesort)
            -> Index lookup on orders using idx_status_cust_created_asc...

The measured response time hovered around 320ms when many rows matched the filter criteria.

Now replace it with an index matching the exact sort order:

ALTER TABLE orders ADD INDEX idx_status_cust_created_desc (status, customer_id ASC, created_at DESC);

Re-running EXPLAIN shows that Using filesort has completely disappeared. The storage engine performs an index lookup and terminates immediately once 20 matching records are reached. Query latency drops from 320ms down to 1.8ms—an improvement of nearly 180x.

4. Production Best Practices for High-Scale Systems

When tables exceed 20 million rows and serve thousands of QPS, an ill-considered DDL command can bring down an entire database cluster. Keep these operational rules in mind when leveraging these MySQL 8 features:

  • Invisible Indexes Do Not Reduce Write Overhead: An invisible index is only hidden from the Optimizer during read operations. Every INSERT, UPDATE, and DELETE still incurs the cost of maintaining the B-Tree. Do not leave dozens of invisible indexes abandoned in your schema; they will quietly consume disk I/O and Buffer Pool capacity.
  • Safe 3-Step Index Decommissioning: When suspecting an index is redundant, mark it INVISIBLE first. Monitor your APM metrics and Slow Query Log for at least 7 to 14 days to capture weekly and monthly reporting cycles. Once all metrics confirm no regressions, safely run DROP INDEX.
  • Primary Keys Cannot Be Hidden: MySQL does not permit setting INVISIBLE on a Primary Key or the first Unique Index acting as an implicit PK. This constraint safeguards data integrity.
  • Column Ordering in Descending Indexes: The golden rule still holds: place equality filter columns (WHERE col = ...) first, followed by columns used in the ORDER BY clause matching their exact sequence and sort direction.
Share: