Sub topic 1
Why Indexes Exist and What They Cost
Prerequisites
This chapter assumes you already know the following:
- Basic SQL:
SELECT,WHERE,JOIN, andORDER BY. - How to create a table and insert rows in Oracle.
- What a table row is, and what a ROWID is. A ROWID is the physical address of a row, and Oracle can use it to fetch that row directly.
- That the optimizer, the part of the database that picks an execution plan for each statement, makes the choice of how to read data.
You do not need to know how indexes are built internally. The next chapter covers that.
The problem an index solves
A table in Oracle is stored as a set of data blocks. A block is the smallest unit of storage Oracle reads from disk, commonly 8 KB. Rows sit in those blocks in no particular order unless you arrange them that way.
Suppose you run this query against a table of ten million orders:
SELECT order_id, status
FROM orders
WHERE customer_id = 42;With no other structure in place, Oracle has only one way to find the matching rows. It reads every block of the table and checks every row against the WHERE condition. This is a full table scan. The cost grows with the size of the table, even if only five rows match.
An index is a separate database object that stores a sorted copy of one or more column values, along with the ROWID of the row each value came from. Because the entries are ordered, Oracle can find a value by walking a small tree of blocks. It does not read the whole structure. It then uses the ROWID to read only the table blocks that hold the matching rows.
A book index works the same way. You look up a word in the sorted list at the back, and it gives you page numbers. You do not read the whole book.
What an index does for a query
An index can help in three ways.
- Fast lookup. A query with a selective predicate, such as
customer_id = 42, reads a few index blocks and a few table blocks, rather than the whole table. - Ordered output. Index entries are already sorted. A query with
ORDER BYon the indexed columns can sometimes skip the sort step. - Constraint enforcement. A
PRIMARY KEYorUNIQUEconstraint needs a fast way to check whether a value already exists. Oracle uses an index for this, and it creates one automatically if none exists.
An index can also let Oracle answer a query without visiting the table at all. If every column the query needs is in the index, Oracle can read the answer from the index alone.
The three index types in this tutorial
This tutorial covers three kinds of index. Each fits a different workload.
| Index type | What it stores | Typical fit |
|---|---|---|
| B-tree | Sorted key values with ROWIDs, in a balanced tree | General purpose, high-cardinality columns, OLTP |
| Bitmap | One bitmap per distinct value, with a bit per row | Low-cardinality columns in read-mostly data |
| Function-based | Results of an expression, stored in a B-tree (or bitmap) | Queries that filter on an expression such as `UPPER(email)` |
Cardinality is the number of distinct values in a column. A status column with four values has low cardinality. An order_id column where every value differs has high cardinality.
A sample table
The chapters that follow use this table.
CREATE TABLE orders (
order_id NUMBER PRIMARY KEY,
customer_id NUMBER NOT NULL,
status VARCHAR2(10) NOT NULL,
order_date DATE NOT NULL,
email VARCHAR2(100)
);
CREATE INDEX orders_cust_date_ix ON orders (customer_id, order_date);The first statement creates the table. Because order_id is declared PRIMARY KEY, Oracle also creates a unique B-tree index on that column, without being asked. The second statement creates a composite index, which is an index on more than one column. Later chapters explain how the order of columns in it matters.
You can see every index on the table in the data dictionary:
SELECT index_name, index_type, uniqueness
FROM user_indexes
WHERE table_name = 'ORDERS';After the statements above, this returns two rows: the system-named index behind the primary key, and ORDERS_CUST_DATE_IX. Both have INDEX_TYPE of NORMAL, which is Oracle's name for a B-tree index.
What indexes cost
Indexes are not free. Every index adds costs in three places.
Storage
An index is a segment of its own and takes disk space and buffer cache space. A composite index on wide columns can be a large fraction of the size of the table. You can measure it:
SELECT segment_name, ROUND(bytes / 1024 / 1024, 1) AS size_mb
FROM user_segments
WHERE segment_name IN ('ORDERS', 'ORDERS_CUST_DATE_IX');Write cost
The index must always agree with the table. Oracle keeps it consistent as part of the same transaction, so every data change pays for it.
INSERT: Oracle adds an entry to every index on the table. Each entry must go into the correct sorted position, which may mean reading an index block, modifying it, and sometimes splitting a full block into two.DELETE: Oracle removes the entry from every index. The row is gone from the table, and each index entry is marked as deleted.UPDATE: If the update changes an indexed column, Oracle removes the old entry and inserts a new one in that index. An update that touches only unindexed columns costs nothing extra for the indexes.
A table with eight indexes pays for nine structures on each insert: the table and eight indexes. The extra work also generates more redo and undo, the logs Oracle uses for recovery and for read consistency.
Optimizer and maintenance cost
More indexes mean more access paths for the optimizer to consider. This usually costs little, but a table with many overlapping indexes can lead to confusing plan choices. Each index also needs optimizer statistics kept current, and each one adds work to backup, recovery, and operations such as moving a table.
Indexes do not always help
Having an index does not mean Oracle will use it. The optimizer compares the estimated cost of each access path and chooses the cheapest one.
Reading through an index is not sequential. For each entry, Oracle may jump to a different table block. If a query returns a large share of the table, those jumps can cost more than one pass over all the blocks. In that case a full table scan is the better plan.
As a rough guide:
- A query that returns a very small fraction of the rows usually benefits from an index.
- A query that returns a large fraction of the rows usually does not.
- The exact crossover depends on the data, the clustering of rows, the block size, and the statistics. There is no fixed percentage.
Small tables are another case. If a table fits in a few blocks, a full scan is cheap and the optimizer will often ignore an index.
Common reasons an index is not used
- The predicate is not selective enough, as described above.
- The query applies a function to the indexed column, such as
WHERE UPPER(email) = 'X', when the index is on plainemail. A function-based index, covered later, fixes this. - The query compares columns of different types, forcing an implicit conversion on the indexed column.
- The query does not use the leading column of a composite index. Later chapters explain why this matters.
- Statistics are missing or stale, so the optimizer misjudges how many rows match.
A way to think about the trade-off
An index shifts work from query time to write time. You pay a small amount on every change so that certain reads become much cheaper. This is a good trade when:
- the table is read far more often than it is written,
- the queries are selective, and
- the same access pattern repeats often enough to justify the upkeep.
It is a bad trade when the table takes heavy bulk loads, when the queries return most of the table, or when no query ever uses the index.
A common pattern for bulk loads into a table is to load first and index afterwards, or to disable maintenance of non-unique indexes during the load and rebuild them. The details depend on the load method, so test it on your own data before relying on it.
Checking whether an index is used
Later chapters show how to read execution plans in detail. The basic check is short. This statement displays the plan Oracle would use for a query:
EXPLAIN PLAN FOR
SELECT order_id
FROM orders
WHERE customer_id = 42
AND order_date >= DATE '2026-01-01';
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);In the output, a line such as INDEX RANGE SCAN with the index name means Oracle chose the index. A line such as TABLE ACCESS FULL means it chose a full table scan. The result depends on the table's size, its data, and its statistics, so the same query can show different plans on different systems.
Summary of the main ideas
- A full table scan reads every block. An index lets Oracle find a few rows without doing that.
- An index stores sorted values and ROWIDs in a separate segment.
- Every insert, delete, and relevant update must also maintain every index, so indexes cost write time, storage, and recovery data.
- The optimizer decides whether to use an index. A query that returns many rows may be faster as a full table scan.
- B-tree, bitmap, and function-based indexes suit different workloads. The rest of the tutorial shows which.
Exercise
A table has 6 indexes. A batch job inserts 1 million rows into it, and a developer says the job is slow. Name two costs the indexes add to this job, and describe one way to reduce them that does not remove the indexes permanently.
Show answer
Each inserted row must add an entry to all 6 indexes, so the job does 7 structure updates per row (the table plus 6 indexes). It also generates more redo and undo and may cause index block splits. To reduce the cost, load the data first and then rebuild or create the non-unique indexes afterwards, or make the non-essential indexes unusable during the load and rebuild them when it finishes. Test this on a copy first.
Exercise
A query SELECT * FROM orders WHERE status = 'SHIPPED' returns 70% of the rows in the table. There is an index on status. Why might the optimizer still choose a full table scan?
Show answer
Reading 70% of the rows through the index means many separate jumps from index entries to table blocks, which usually costs more than reading the table blocks once in order. The optimizer estimates both costs and picks the cheaper one, which here is likely the full scan.
Exercise
An UPDATE changes only the email column of one row in orders, using the indexes created in this chapter. Which indexes need maintenance?
Show answer
None of the two indexes shown. The primary key index covers order_id and ORDERS_CUST_DATE_IX covers customer_id and order_date, and the update changes neither. Only indexes that include email need work, and none exist yet.