Sub topic 1
Why Indexes Exist and What They Cost
Prerequisites
This chapter assumes you can write basic SQL with SELECT, WHERE, and ORDER BY. You should be able to create a table and insert rows in Oracle. You should also know that the optimizer chooses an execution plan for each query.
Why Indexes Exist
An index is a separate structure that maps column values to the physical location of matching rows, called a ROWID. Without an index, Oracle can find matching rows only by reading every row in the table. That read is a full table scan.
An index lets Oracle jump to the matching rows. Each INSERT, UPDATE, and DELETE must also update every index on the table. Indexes therefore cost disk space and slow down writes.
How a B-tree Index Is Organized
The default index type in Oracle is the B-tree, short for balanced tree. Its blocks form levels: a root block, optional branch blocks, and leaf blocks. Leaf blocks hold sorted key values, each paired with a ROWID. Every leaf sits at the same depth, so a lookup reads only a few blocks even on large tables.
Creating B-tree, Unique, and Composite Indexes
A primary key creates a unique B-tree index automatically. You can also create indexes yourself.
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);
CREATE UNIQUE INDEX orders_email_uq ON orders (email);A composite index covers more than one column. Oracle can use its leading column, customer_id, for lookups on that column alone. It can use the index for customer_id plus order_date together. A filter on order_date alone usually cannot use it efficiently.
Index Scans and Full Table Scans
Check which access path Oracle chooses with EXPLAIN PLAN.
EXPLAIN PLAN FOR
SELECT order_id
FROM orders
WHERE customer_id = 42;
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);An INDEX RANGE SCAN means Oracle reads the index and then the matching table rows. A TABLE ACCESS FULL means Oracle reads the whole table.
> Callout note: The optimizer may choose a full table scan even when an index exists. If a query matches a large share of the rows, reading the table directly is often cheaper.
Note: the callout above uses a block quote marker in the prose, so it is replaced below with the required callout fence.
Exercise
Table orders has the composite index orderscustdateix on (customerid, orderdate). Will a query that filters only on orderdate be able to use this index efficiently? Why or why not?
Show answer
Usually not. The index is sorted by customerid first, so rows with a given orderdate are spread across all customerid values. Oracle would need to scan the whole index, so a full table scan is often cheaper. An index on orderdate alone would serve that query.