Reversing a D1 Composite Index: Query Plan Impact
In this article
- What a Composite Index Actually Stores
- How the Optimizer Uses Index Order
- Plan Changes You Will See
- Why Reversing Sort Direction Matters
- How to Predict the Impact
- Common Problems and Misconceptions
- Comparing Reversal to Other Index Changes
- Costs and Safety Considerations
- Alternatives to Reversing the Index
- Frequently Asked Questions
Reversing a D1 composite index (changing its column order or sort direction) forces the query optimizer to re-evaluate every execution plan that referenced the old index, often resulting in a different plan—sometimes faster, sometimes slower. This article explains exactly what changes in the query plan, why it happens, and how to predict the impact before you make the change.
What a Composite Index Actually Stores
A composite index (also called a concatenated or multi-column index) is a single B-tree structure that sorts rows by the first column, then by the second within ties, and so on. For an index on (col1, col2), the database physically orders entries by col1, and only when col1 values are equal does it use col2 to break ties. Reversing the index—say to (col2, col1)—changes the entire sort order of the B-tree. The query plan's index access path must match this order to be efficient.
How the Optimizer Uses Index Order
The query optimizer reads the index metadata (column order, sort direction, uniqueness) and decides whether an index can satisfy a query's WHERE, ORDER BY, or GROUP BY clauses. When you reverse the column order, the optimizer sees a different set of "leading columns." For example, an index on (last_name, first_name) can efficiently find all rows with a specific last_name; reversing it to (first_name, last_name) means a query filtering on last_name can no longer use a simple index seek—it must either scan the whole index or use a different index. The plan changes from an index seek to an index scan or a table scan.
Plan Changes You Will See
Reversing a composite index can alter several parts of the execution plan:
- Access method: Seek vs. scan. A seek retrieves only matching rows; a scan reads all entries. Reversing columns can turn a seek into a scan if the query's filter no longer matches the leading column.
- Join strategy: Nested loop, hash join, or merge join. A merge join often requires both inputs sorted on the join key; if the index no longer provides that sort, the optimizer may switch to a hash join or add a sort operator.
- Sort operations: An
ORDER BYon the original column order could be satisfied by the index (no sort). After reversal, the index no longer provides that order, so the plan gains aSortoperator. - Key lookups: If the index becomes less selective, the optimizer may choose to use a different index plus lookups, or a full scan.
Why Reversing Sort Direction Matters
Reversing the sort direction (e.g., from ascending to descending) on a column also changes the index's physical order. Most B-trees can be traversed forward or backward, but a mixed sort (one column ascending, another descending) often cannot use a single index for both. For instance, an index on (col1 ASC, col2 ASC) cannot efficiently satisfy ORDER BY col1 ASC, col2 DESC—the optimizer must add a sort. Reversing the index to (col1 ASC, col2 DESC) fixes that, but breaks queries that need col2 ASC. The plan changes accordingly: sort operators appear or disappear, and seek predicates change.
How to Predict the Impact
Before reversing an index, you can estimate the plan impact by checking the queries that reference it:
- Find all queries that use the index (via query store, DMVs, or EXPLAIN).
- For each query, note the columns in
WHERE,ORDER BY, andJOINclauses. - Check if the new leading column appears in those clauses. If yes, the index may still be useful; if no, expect a scan or a different index.
- Use the database's query plan analyzer to compare the estimated costs before and after (you can test on a staging server).
Remember that reversing an index also affects UPDATE, INSERT, and DELETE performance—the index must be maintained in the new order, which can cause page splits and fragmentation.
Common Problems and Misconceptions
A frequent misconception is that reversing an index is a trivial metadata change. In reality, the database must rebuild the entire index, which can take significant time and I/O on large tables. During the rebuild, the index may be unavailable or use extra disk space. Another common issue: developers reverse an index to fix a slow query, but inadvertently slow down other queries that relied on the old order. Always test the full workload, not just the one query.
Another problem is assuming that a composite index with columns in any order is equally useful. The leading column is the only one that can be used for equality or range seeks without additional filtering. If you reverse the index, you change which column is "leading," so queries that filter on the new second column lose the seek ability.
Comparing Reversal to Other Index Changes
Reversing a composite index is one of several possible alterations:
- Adding a column to the index (e.g., as an included column) can improve covering but increases index size.
- Dropping a column reduces size but may lose the ability to cover queries.
- Changing sort direction (ASC/DESC) is similar to reversal but only affects the order of one column.
- Reordering columns is exactly what we discuss here—it changes the leading column and thus the access path.
Each change forces the optimizer to recompile dependent plans, but reversal is often more disruptive because it changes the fundamental sort order.
Costs and Safety Considerations
The main costs of reversing an index are:
- Rebuild time: For a large table, this can be hours.
- Disk space: The rebuild may require additional space for the new index.
- Locking: Depending on the database and online rebuild options, the table may be locked, affecting concurrent queries.
- Plan invalidation: All cached plans using the old index are invalidated, causing a burst of recompilations.
Before making the change, ensure you have a rollback plan (keep the old index definition script). Test on a replica or staging environment first. Also, monitor the query store or performance dashboard for regressions after the change.
Alternatives to Reversing the Index
If you need to support queries that filter on different columns, consider these alternatives instead of reversing a single composite index:
- Create a second index on the other column order. This adds storage but avoids disrupting existing plans.
- Use included columns to make an index covering without changing the sort order.
- Rewrite the query to use a different access path, such as a hint or a different join order.
- Use a columnstore index if the workload is analytical and you need high compression and scan performance.
Each alternative has trade-offs; the best choice depends on your query mix and storage constraints.
Frequently Asked Questions
Will reversing an index always slow down queries? No. If the new leading column matches your most frequent filter, the index may become faster for those queries. But queries that relied on the old order will likely slow down.
Does reversing an index change the data in the table? No, only the index structure changes. The table data remains untouched.
Can I reverse an index without rebuilding it? No, you must alter the index definition, which triggers a rebuild in most databases.
How do I see the current query plan before reversing? Use EXPLAIN (or SET SHOWPLAN_ALL in SQL Server, EXPLAIN ANALYZE in PostgreSQL) to capture the plan for the affected queries.
What is the difference between reversing columns and changing sort direction? Reversing columns changes the order of columns in the index key (e.g., from (a,b) to (b,a)). Changing sort direction keeps the column order but flips ASC/DESC for one or more columns. Both affect the index's ability to satisfy ORDER BY and seek predicates.
Should I use a hint to force the old plan after reversing? Hints are a temporary workaround, not a long-term solution. It's better to adjust the index or query to match the new structure.