Validate MySQL index changes with invisible indexes

Validate MySQL index changes with invisible indexes

Validate MySQL index changes with invisible indexes

An order-list query filters by customer and status, then returns the twenty most recent records. Database CPU is not saturated, yet response times increase as the data grows. Adding a composite index directly may improve reads, but it can also increase write overhead. A reliable change process preserves the original plan, makes an invisible index available to a single test session, and then validates query gains and maintenance costs separately. One faster query execution is not enough to sign off on a rollout.

1. Keep validation within an isolated test database

This article uses MySQL 8.4, InnoDB, and ordinary secondary indexes. Run the commands in an already connected SQL session. Start with the example on an isolated instance: the database and table names refer only to test objects, not production tables. An invisible index does not provide resource isolation. Testing on the same instance still consumes CPU, memory, and disk IO.

Runner’s AMD EPYC 7543P dedicated servers provide DDR4-3200 ECC memory in two capacities, 128GB / 256GB, along with two independently, directly attached 1TB NVMe drives. More memory can improve cache hit rates, but it cannot replace the right query access path. There is no hardware RAID, and index experiments are no substitute for data backups.

Before testing, record the version, table definition, existing indexes, data volume, and target SQL. Anonymize samples from real workloads while preserving the distribution of data across customers, the proportions of each status, and the distribution over time. Avoid copying only a small, uniformly distributed sample.

An invisible index is still built, stored, and maintained. Invisibility only changes whether the optimizer considers it by default; it does not eliminate index-building work or write costs.

2. Establish a reproducible query baseline

The following script generates one thousand test orders. This dataset is intended to verify the workflow, not to demonstrate production performance. Before running it, confirm that the isolated instance does not already contain a test database with the same name, so that old data does not get mixed in.

CREATE DATABASE index_lab;
USE index_lab;

CREATE TABLE orders_probe (
    id BIGINT UNSIGNED NOT NULL PRIMARY KEY,
    customer_id INT UNSIGNED NOT NULL,
    status VARCHAR(16) NOT NULL,
    created_at DATETIME NOT NULL,
    amount_cents INT UNSIGNED NOT NULL
) ENGINE=InnoDB;

INSERT INTO orders_probe
    (id, customer_id, status, created_at, amount_cents)
WITH RECURSIVE seq AS (
    SELECT 1 AS n
    UNION ALL
    SELECT n + 1 FROM seq WHERE n < 1000
)
SELECT
    n,
    MOD(n, 100),
    IF(MOD(n, 3) = 0, 'paid', 'pending'),
    TIMESTAMPADD(SECOND, n, '2026-10-11 00:00:00'),
    n * 100
FROM seq;

ANALYZE TABLE orders_probe;

EXPLAIN FORMAT=TREE
SELECT id, created_at, amount_cents
FROM orders_probe
WHERE customer_id = 42 AND status = 'paid'
ORDER BY created_at DESC
LIMIT 20;

Save the full plan text, paying attention to the access path, estimated row counts, and whether there is a separate sort node. With no secondary index matching the filter conditions, the baseline will usually include a table scan and a sort. The actual output depends on the current instance, however; do not substitute a supposed standard result.

Validation also requires recording the query results. The example uses unique timestamps, so the ordering is unambiguous. If real data contains identical timestamps, add a stable sort key and review the index design again. Otherwise, a difference in row order between two executions does not necessarily indicate an index-related data error.

3. Make the candidate index available only to the current session

The composite index starts with the two equality-filter columns, followed by the sort column. This order is designed for the specific query in this article, not as a template for every query. Omitting the customer condition, switching to a range filter, or changing the sort order requires a separate review.

ALTER TABLE orders_probe
    ADD INDEX idx_customer_status_created
    (customer_id, status, created_at) INVISIBLE;

SHOW INDEX FROM orders_probe;

SET @saved_optimizer_switch = @@SESSION.optimizer_switch;

SET SESSION optimizer_switch = 'use_invisible_indexes=off';

EXPLAIN FORMAT=TREE
SELECT id, created_at, amount_cents
FROM orders_probe
WHERE customer_id = 42 AND status = 'paid'
ORDER BY created_at DESC
LIMIT 20;

SET SESSION optimizer_switch = 'use_invisible_indexes=on';

EXPLAIN FORMAT=TREE
SELECT id, created_at, amount_cents
FROM orders_probe
WHERE customer_id = 42 AND status = 'paid'
ORDER BY created_at DESC
LIMIT 20;

SET SESSION optimizer_switch = @saved_optimizer_switch;

Run the entire sequence on the same connection and restore the original setting before finishing. If an error occurs partway through, still execute the final restoration statement, or close the test connection. Do not return a connection with this switch enabled to the application’s connection pool.

SHOW INDEX should report the candidate index as invisible. Enabling the switch only makes the index eligible for use; it does not guarantee that the optimizer will choose it. Small tables, in particular, may still be scanned. The switch also makes other invisible indexes accessible to the current session eligible for use, so check existing candidates as well when testing real tables.

The amount column is not included in this index, so reading it may still require a lookup in the clustered index. An index scan alone does not mean the query is covered by the index.

4. Turn plan changes into verifiable evidence

A regular EXPLAIN provides estimates without executing the target query. EXPLAIN ANALYZE actually executes the query and reports iterator information. Use it only for controlled, read-only SQL. Check the expected result size and cost first; it is not an observation command with no workload impact.

Test read gains and write costs separately

Using the same representative dataset, repeat tests with the switch off, then on, then off again. This helps avoid mistaking cache warm-up for an index benefit. Keep parameters, concurrency, returned columns, and background load consistent. Record actual execution times, rows scanned, and changes in sorting rather than accepting the single fastest run.

You cannot compare write costs by toggling visibility, because the index is maintained in both states. Use two isolated copies: one without the candidate index and one with it. Replay the same insert and update workload against both. Compare write latency, throughput, and index storage usage. Do not replay test data directly into the production primary database.

Cover at least customers with many orders, customers with few orders, conditions that return no results, and ranges reaching far back into historical data. Also check related queries for regressions. If the candidate index is used but its benefits are inconsistent, examine statistics and sample distribution before rushing to pin the plan with FORCE INDEX.

5. Validate rollout and rollback separately

Before building the index in production, check for long-running transactions and metadata lock waits, and confirm that enough disk space is available. Making an index invisible does not prevent DDL from acquiring metadata locks. Even explicitly requesting an online algorithm does not mean there will be no waits. In a replicated setup, also monitor how the index build affects replication progress.

First, rehearse visibility changes on the test table:

ALTER TABLE orders_probe
    ALTER INDEX idx_customer_status_created VISIBLE;

ALTER TABLE orders_probe
    ALTER INDEX idx_customer_status_created INVISIBLE;

Making the index invisible again excludes it from consideration for sessions using the default setting, but it does not reclaim index space or stop maintenance overhead. Sessions with invisible-index use enabled may still use it, so rollback checks must include application connection settings. Once you have decided to abandon the candidate, assess the impact of dropping it separately. Do not combine removal and rollback into a single step.

The final record should include before-and-after plans, query-result consistency checks, performance with representative parameters, the write comparison, lock waits, and recovery steps. The index change is complete only when all of this evidence has been checked together. “Index created successfully” and “query uses the index” are only intermediate states.

Frequently asked questions

Does an invisible MySQL index still consume space and add write overhead?

Yes. It occupies storage and is maintained during inserts, updates and deletes. Invisibility only changes whether the optimizer considers it by default; it does not remove index creation or maintenance costs.

Will enabling invisible indexes for a session force the optimizer to use one?

No. use_invisible_indexes=on only makes invisible indexes eligible. Statistics, data distribution and estimated costs still determine the plan. Check the selected index, rows examined and sorting rather than treating a forced index as the default acceptance test.

Runner EPYC 7543P Dedicated Server

From $450/month

Configure a Runner system, starting with memory

Dedicated AMD EPYC 7543P server with 128 GB or 256 GB DDR4-3200 ECC memory.