Sub topic 3
Indexing expressions with function-based indexes
This chapter assumes you know basic SELECT, WHERE, and CREATE TABLE in Oracle, and that you have seen B-tree indexes before. A function-based index is an index on the result of an expression, such as UPPER(email), instead of on the raw column.
Indexing expressions with function-based indexes
A plain B-tree index stores column values as they are. If a query wraps the column in a function, Oracle usually cannot use that index. A function-based index stores the computed value, so the optimizer can search it directly.
CREATE INDEX orders_email_upper_ix ON orders (UPPER(email));The function must be deterministic, meaning it returns the same result for the same input every time. Functions such as UPPER, LOWER, and TRUNC qualify.
Making queries match a function-based index
The query must use the same expression as the index definition. The optimizer does not match LOWER(email) against an index on UPPER(email).
SELECT order_id
FROM orders
WHERE UPPER(email) = '[email protected]';Check the plan with EXPLAIN PLAN. An index range scan confirms the index is used. A full table scan means the expressions do not match.
Indexing a virtual column instead
A virtual column holds an expression that Oracle computes on read and stores no data for. Indexing it gives the same benefit and makes the expression visible in the table definition.
ALTER TABLE orders ADD (
email_uc VARCHAR2(100) GENERATED ALWAYS AS (UPPER(email)) VIRTUAL
);
CREATE INDEX orders_email_uc_ix ON orders (email_uc);
SELECT order_id
FROM orders
WHERE email_uc = '[email protected]';Queries must then reference email_uc by name.
Choosing among the three index types
Use a B-tree index for selective values on columns that are filtered as they are. Use a bitmap index for low-cardinality columns in read-mostly tables. Bitmap indexes cause lock contention under concurrent DML, so avoid them on busy transaction tables. Use a function-based index when queries consistently wrap a column in a deterministic function.
Testing and maintaining indexes
Before you drop an index, make it invisible. The optimizer then ignores it, and you can compare plans without losing the index.
ALTER INDEX orders_cust_date_ix INVISIBLE;
-- run the test query and compare the plan
ALTER INDEX orders_cust_date_ix VISIBLE;After large data loads, gather statistics so the optimizer has current information. Rebuild an index that has grown unevenly with ALTER INDEX orders_email_upper_ix REBUILD;.
Exercise
A table has an index on UPPER(email). Will a query that filters on LOWER(email) use it?
Show answer
No. The expression in the query must match the index definition, so LOWER(email) cannot use an index on UPPER(email).