Sub topic 14
Testing and Maintaining Indexes
This chapter assumes you can create B-tree, bitmap, and function-based indexes, read a plan from DBMS_XPLAN.DISPLAY, and know that the optimizer picks plans from statistics. It covers how to test whether an index is worth keeping, how to keep optimizer statistics current, and when an index needs a rebuild.
Why indexes need ongoing care
Every index costs something on each insert, update, and delete, and it takes space. An index that no query uses still pays that cost. Indexes can also go stale in two ways:
- The data changes, so statistics on the table and index no longer describe it. The optimizer then misjudges costs.
- Heavy deletes and updates leave sparse index blocks, so the index is larger than it needs to be.
The work in this chapter has three parts: test a change safely, keep statistics fresh, and rebuild only when there is a reason.
Testing with invisible indexes
An invisible index is still maintained by every DML statement, but the optimizer ignores it by default. You can use this to ask "what happens if this index is gone?" without dropping it. If a query slows down, you make the index visible again at once. No rebuild is needed, because the index never stopped being maintained.
ALTER INDEX orders_cust_date_ix INVISIBLE;
-- run the workload or the test query and compare plans
ALTER INDEX orders_cust_date_ix VISIBLE;You can also create an index as invisible, so you can check it before any production query depends on it:
CREATE INDEX orders_status_date_ix
ON orders (status, order_date) INVISIBLE;To try an invisible index in your own session only, set a session parameter. Other sessions keep ignoring it.
ALTER SESSION SET optimizer_use_invisible_indexes = TRUE;
EXPLAIN PLAN FOR
SELECT order_id
FROM orders
WHERE status = 'OPEN'
AND order_date >= DATE '2026-01-01';
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);You can see the current state in the data dictionary:
SELECT index_name, index_type, visibility, status
FROM user_indexes
WHERE table_name = 'ORDERS';What invisibility does not do
- It does not stop maintenance. Inserts, updates, and deletes still update the index, so you do not save any DML cost while it is invisible.
- It does not stop unique enforcement. An invisible unique index still rejects duplicates.
- It does not always hide the index from everything. Oracle can still use an invisible index on a foreign key column to avoid a table lock on the parent table when you change parent keys. Check that before you decide a foreign key index is unused.
- It does not prove an index is unneeded. A test query that you did not think of, such as a month-end report, may still depend on it. Test across a full business cycle where you can.
Finding indexes worth testing
A workable routine is to list candidates, make them invisible one at a time, watch the workload, and then decide. Oracle can record whether an index was used with index usage tracking. In Oracle Database 12.2 and later, the view V$INDEX_USAGE_INFO and the dictionary view DBA_INDEX_USAGE summarize how often indexes were accessed. In 23ai, tracking is enabled by default. In earlier releases, check which tracking feature your version provides before you rely on it.
SELECT name, total_access_count, last_used
FROM dba_index_usage
WHERE owner = 'APP'
ORDER BY total_access_count;Treat the result as a hint. Sampling can miss rare accesses, and an index that enforces a primary key, unique, or foreign key constraint has value even if no query ever reads it.
Statistics on indexes
The optimizer estimates the cost of an index access path from statistics. For a B-tree index, the main ones are:
| Statistic | Meaning | Why the optimizer cares |
|---|---|---|
| `BLEVEL` | Height of the B-tree above the leaf level | Number of block reads to reach a leaf |
| `LEAF_BLOCKS` | Number of leaf blocks | Cost of a range scan |
| `DISTINCT_KEYS` | Number of distinct key values | Selectivity of an equality predicate |
| `CLUSTERING_FACTOR` | How well the table row order matches the index order | Cost of fetching rows after the index lookup |
| `NUM_ROWS` | Rows in the index | Cardinality estimates |
A high clustering factor, close to the number of rows, means that consecutive index entries point to different table blocks. A range scan then does many single-block reads. A low value, close to the number of table blocks, means the rows are stored in nearly the same order as the index. The optimizer may reject an index with a poor clustering factor even when the predicate is selective.
Index statistics are gathered when you create or rebuild an index. Oracle also gathers them with table statistics when you use CASCADE, which is the default through AUTO_CASCADE. To gather them yourself:
BEGIN
DBMS_STATS.GATHER_TABLE_STATS(
ownname => USER,
tabname => 'ORDERS',
cascade => TRUE
);
END;
/To gather statistics for one index:
BEGIN
DBMS_STATS.GATHER_INDEX_STATS(
ownname => USER,
indname => 'ORDERS_CUST_DATE_IX'
);
END;
/Then look at the result:
SELECT index_name, blevel, leaf_blocks, distinct_keys,
clustering_factor, num_rows, last_analyzed
FROM user_indexes
WHERE table_name = 'ORDERS';Statistics for function-based and virtual column indexes
An index on UPPER(email) has a hidden virtual column behind it. The optimizer needs statistics on that expression to estimate selectivity. Gathering table statistics with default settings covers the hidden column in most cases. If you index an explicit virtual column, as in email_uc, gather statistics on the table again after you add it, so the new column is included.
When to rebuild an index
Oracle B-tree indexes maintain their balance. They do not need regular rebuilds to stay fast. Rebuilding on a schedule is a common habit, but it often costs more than it returns: the rebuild uses I/O and redo, and the index grows again as new rows are inserted into the space you just compacted.
A rebuild is reasonable in these cases:
- The index is
UNUSABLE, for example after a partition operation or aMOVEof the table. - A large batch delete has left many sparse leaf blocks, and the table will not refill that range soon.
- You want to move the index to another tablespace or change its storage attributes.
Check the status first:
SELECT index_name, status
FROM user_indexes
WHERE status <> 'VALID';Then rebuild online so that DML on the table can continue:
ALTER INDEX orders_cust_date_ix REBUILD ONLINE;An online rebuild needs room for both the old and the new index at the same time, and it holds brief locks at the start and end. It works best when you run it in a quiet period.
Rebuild versus coalesce
COALESCE merges adjacent sparse leaf blocks inside the existing index, and it does not allocate a new segment. It is lighter than a rebuild and does not need double the space. It does not change the height of the tree and does not move the index.
ALTER INDEX orders_cust_date_ix COALESCE;| Operation | Space needed | Can lower tree height | Typical use |
|---|---|---|---|
| `REBUILD ONLINE` | Old and new index at once | Yes | Unusable index, move, large clean-up |
| `COALESCE` | Little extra | No | Light compaction after deletes |
| `DROP` and `CREATE` | Only the new index | Yes | Definition change |
Bitmap indexes and rebuilds
Bitmap indexes can become fragmented after heavy DML on the table, because each change may split or rewrite bitmap segments. They are meant for read-mostly data, so a rebuild after a large load is a normal step. Plan it into the load job: disable or drop the bitmap index, load, then rebuild. Rebuilding is usually faster than maintaining the bitmaps row by row during a large load.
A maintenance checklist
- Gather statistics with
CASCADE => TRUEafter large data changes. - Check
STATUSinUSER_INDEXESandUSER_IND_PARTITIONSforUNUSABLEentries. - Test unused-looking indexes by making them invisible, not by dropping them.
- Keep constraint-backing and foreign key indexes unless you have a clear reason.
- Rebuild only for a stated reason, and prefer
ONLINEon live tables. - After any change, compare plans with
EXPLAIN PLANto confirm the result.
Common mistakes
- Dropping an index that looks unused from usage data that covers only a short period.
- Rebuilding every index weekly, which creates redo and I/O work and often leaves the index no faster.
- Forgetting that an invisible index still slows DML.
- Running an
ALTER INDEX ... REBUILDwithoutONLINEon a busy table, which blocks DML on the table while it runs. - Testing a plan in a session where
optimizer_use_invisible_indexesis set, and then forgetting that other sessions do not see the same plan.
Exercise
Your team suspects that the index ORDERSCUSTDATE_IX is not used. Describe a safe way to check this, and say what you would do first if a report slows down during the test.
Show answer
Run ALTER INDEX orderscustdateix INVISIBLE so the optimizer ignores the index while Oracle keeps maintaining it. Run the normal workload, including period-end jobs, and compare plans and timings. If a report slows down, run ALTER INDEX orderscustdateix VISIBLE. This takes effect at once and needs no rebuild, because the index was maintained the whole time. Drop the index only after a full business cycle shows no harm.
Exercise
A nightly job deletes 80 percent of the rows in a table. Afterwards, an index on the table is much larger than its contents need, and no new rows will arrive in that range. Which maintenance command would you choose, and why would you add ONLINE?
Show answer
Use ALTER INDEX ... REBUILD ONLINE, because the delete left many sparse leaf blocks and a rebuild returns the space and can lower the tree height. If space is tight, ALTER INDEX ... COALESCE is a lighter option, although it does not lower the height. ONLINE lets other sessions keep running DML on the table during the rebuild. Gather statistics afterwards so the optimizer sees the new size.