Sub topic 13
Choosing among the three index types
This chapter assumes you can create B-tree, bitmap, and function-based indexes, and that you can read an EXPLAIN PLAN output well enough to tell an INDEX RANGE SCAN from a TABLE ACCESS FULL. It also assumes you know that the optimizer is cost-based and picks a plan from statistics. The goal here is to turn those pieces into a repeatable decision.
Decide from the query and the workload
Start with the query, not the index type. For each candidate index, answer these questions in order:
- What does the predicate look like? Does it compare a bare column, or does it wrap the column in an expression?
- How selective is it? That is, what fraction of the table's rows does the predicate return?
- How many distinct values does the column have, and how are the rows spread across them?
- Who changes the table, and how often? Is it single-row OLTP DML, bulk loads, or a nightly batch?
The first question separates function-based indexes from the others. The second and third separate B-tree from bitmap. The fourth rules bitmap in or out. A function-based index is not a third kind of structure in the way bitmap is. By default it is a B-tree whose keys are computed from an expression, so choosing it answers the question "what is being indexed," while choosing B-tree or bitmap answers the question "how is it stored."
Side-by-side comparison
| Property | B-tree | Bitmap | Function-based |
|---|---|---|---|
| Best column shape | High cardinality, or unique | Low cardinality | Any column wrapped in an expression in the query |
| Typical workload | OLTP, mixed read and write | Data warehouse, read-mostly | Same as the underlying type |
| Enforces uniqueness | Yes | No | Yes, if created as `UNIQUE` |
| Indexes rows where all key columns are NULL | No | Yes | No (default B-tree behavior) |
| Cost of concurrent DML | Row-level contention is low | One bitmap entry covers many rows, so sessions block each other | Same as the underlying type, plus expression evaluation on each DML |
| Edition | All editions | Enterprise Edition | Check your edition and version documentation |
| Combines well with other indexes | Through join and nested loops, or conversion | Natively with `AND`, `OR`, `NOT` on bitmaps | Same as the underlying type |
When B-tree is the answer
B-tree is the default, and you should need a reason to pick anything else. Choose it when:
- The predicate returns a small fraction of the table, such as
order_id = :idor a single customer's orders. - You must enforce a
PRIMARY KEYorUNIQUEconstraint. - The table takes frequent concurrent inserts, updates, and deletes.
- You need ordered access, for example
ORDER BY order_datethat the index can satisfy without a sort.
For multi-column predicates, the composite order from the earlier chapter still applies. Put the columns your queries always filter by with equality first. Put range columns later. (customer_id, order_date) serves WHERE customer_id = 42 AND order_date >= ..., and it also serves WHERE customer_id = 42 alone. It does not serve WHERE order_date >= ... well on its own, although an index skip scan can sometimes help when the leading column has few distinct values.
A low-selectivity predicate defeats a B-tree. If status = 'SHIPPED' matches 60% of the rows, reading the index and then fetching each row by ROWID costs more than one multiblock read of the table. The optimizer will usually choose the full scan, and the index will cost you maintenance for nothing.
When bitmap is the answer
A bitmap index becomes attractive when three things are all true:
- The column has few distinct values compared to the row count, such as
status, a region code, or a flag. - Queries combine several such columns with
ANDandOR. The optimizer can merge the bitmaps (BITMAP AND,BITMAP OR) before touching the table, so each index alone may be unselective while the combination is very selective. - The table is loaded in batches and read by many queries, not updated row by row by many sessions.
The last condition is the one that fails most often in practice. A bitmap entry covers a range of rows for one key value. When a session inserts or updates a row, Oracle locks the bitmap entries it changes, and that locks every row that entry covers. A second session changing a row with the same key value, or one that falls into the same entry, waits. A table with a bitmap index on status and 50 sessions inserting orders will serialize on the few status values in use. If the workload is OLTP, use B-tree, or no index.
Bitmap indexes also have a licensing and edition constraint: they are an Enterprise Edition feature. Confirm this before you build a design that depends on them.
When function-based is the answer
Use a function-based index when the predicate must stay as an expression. The classic case is a case-insensitive lookup:
SELECT order_id
FROM orders
WHERE UPPER(email) = '[email protected]';A plain index on email cannot be used here, because the stored keys are the original values and the predicate asks about transformed values. An index on UPPER(email) stores the transformed keys, so the lookup is a normal index range scan.
Two requirements apply:
- The query expression must match the indexed expression.
UPPER(email)matchesUPPER(email). It does not matchLOWER(email), and it does not matchUPPER(TRIM(email)). - Every function in the expression must be deterministic, meaning the same input always gives the same output. Built-in functions like
UPPERqualify. If you write a PL/SQL function for the index, declare itDETERMINISTICand make sure it really is.
If you can change the query, you can sometimes avoid the index. Store the data in the form you search. If you cannot change the data, use the function-based index.
Function-based index or virtual column?
Both give you the same lookup benefit. The difference is where the expression lives.
| Question | Function-based index | Index on a virtual column |
|---|---|---|
| Expression visible in the table definition | No, it lives only in the index | Yes, it is a named column |
| Query can refer to the expression by name | No, it must repeat the expression | Yes, `WHERE email_uc = ...` |
| Changes the table definition | No | Yes, it adds a column |
| Optimizer statistics on the expression | Hidden column statistics | Normal column statistics |
Prefer the virtual column when several queries, constraints, or developers will use the same expression, because the definition then exists in one place. Prefer the function-based index when you want no change to the table's shape.
Worked decisions on the orders table
Here is how the decision applies to the orders table from this tutorial.
WHERE order_id = :id. Selective and unique. The primary key's B-tree index already handles it.WHERE customer_id = :c AND order_date >= :d. Selective, with an equality column followed by a range column. Use the composite B-tree(customer_id, order_date).- Reports counting orders by
statusand other low-cardinality attributes, run against a warehouse copy loaded nightly. Bitmap onstatusis a fit. The same index on the live OLTP table is not. WHERE UPPER(email) = :e. The column is wrapped, so use a function-based index or a virtual column index.
After you create an index, confirm that the optimizer uses it. Compare the plan to the one you had before:
EXPLAIN PLAN FOR
SELECT order_id
FROM orders
WHERE UPPER(email) = '[email protected]';
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);Look for an INDEX RANGE SCAN on the index you built. If you see TABLE ACCESS FULL, check these causes in order:
- The expression in the query does not match the indexed expression.
- The table is small, so a full scan is cheaper.
- Statistics are stale, so the optimizer misjudges selectivity.
- The predicate matches too large a share of the rows.
Testing a choice before you commit
You can test a candidate without dropping it. An invisible index is still maintained on DML, but the optimizer ignores it by default:
ALTER INDEX orders_cust_date_ix INVISIBLE;
-- Compare plans and timings for the real workload here.
ALTER SESSION SET OPTIMIZER_USE_INVISIBLE_INDEXES = TRUE;
-- Re-run the test query in this session to see the plan with the index.
ALTER INDEX orders_cust_date_ix VISIBLE;If performance is unchanged with the index invisible, the index is a candidate for removal. Because the index stays current while invisible, making it visible again is instant, with no rebuild. Remember that an invisible index still costs DML time and storage. Only dropping it removes that cost.
Common mistakes
- Indexing every column "just in case." Each index adds work to every insert and delete, and to updates of its columns.
- Choosing bitmap because a column has few values, without checking who writes to the table.
- Creating a function-based index and writing the query with a slightly different expression.
- Creating a B-tree on a column where the predicate returns most of the table.
- Judging an index from the plan on a tiny test table. Test with realistic row counts and statistics.
Exercise
A table tickets has 20 million rows. The column priority has 4 distinct values. Many support agents insert and update tickets all day. A nightly report counts tickets by priority and region. Which index type would you choose for priority on this table, and why? What would change if the report ran against a separate copy loaded once a night?
Show answer
Do not use a bitmap index on the live table. Many sessions change rows concurrently, and each change locks the bitmap entry for its priority value, which covers many rows, so agents would block each other. A B-tree on priority would likely not help the report either, because each value matches a large share of the rows, so the optimizer would prefer a full scan. The sensible choice is no index on priority for the live table, or a composite B-tree if a selective predicate also uses it. On a copy loaded once a night and read by reports, a bitmap index on priority and region suits the workload (given Enterprise Edition), because there is no concurrent DML and the optimizer can merge the two bitmaps with BITMAP AND or BITMAP OR.
Exercise
You created CREATE INDEX orders_email_upper_ix ON orders (UPPER(email));. A developer reports that WHERE LOWER(email) = '[email protected]' still shows TABLE ACCESS FULL. Why, and what are two ways to fix it?
Show answer
The query expression LOWER(email) does not match the indexed expression UPPER(email), so the optimizer cannot use the index. One fix is to rewrite the query to WHERE UPPER(email) = '[email protected]'. The other is to create a second function-based index on LOWER(email), which adds maintenance cost. Standardizing on one expression, ideally as a virtual column, avoids the mismatch.