Indexes, Execution Plans and Optimiser Statistics

Article · 7:00

B-tree and bitmap indexes and when each is wrong, reading DBMS_XPLAN, statistics and histograms, bind peeking, and partitioning with its licence.

Reading a plan. EXPLAIN PLAN shows what the optimiser would do; DBMS_XPLAN.DISPLAY_CURSOR with the ALLSTATS LAST format shows what it did, including actual rows beside estimated rows. Use the second. The comparison between E-Rows and A-Rows is the single most useful diagnostic in Oracle - an order-of-magnitude gap means the optimiser is choosing on bad information, and fixing the estimate is better than forcing the plan.

Indexes. B-tree is the default and serves equality, ranges and ordering. Oracle does not store NULLs in a plain B-tree index, which is why WHERE col IS NULL cannot use one - a well-known source of surprise.

Bitmap indexes store a bitmap per distinct value. On a low-cardinality column in a warehouse they are extremely compact and combine beautifully: several bitmap indexes can be ANDed to resolve a multi-column predicate. On an OLTP table they are a serious mistake - updating one row locks an entire bitmap segment covering many rows, and concurrent DML collapses. The rule is: bitmap for read-mostly warehouses, never for transactional tables.

Other types worth knowing: function-based indexes (the only way to index UPPER(name)), reverse key indexes to spread inserts of sequential values across leaf blocks in RAC, and index-organised tables, which store the table in the primary key's B-tree.

Statistics. DBMS_STATS gathers them. The defaults are mostly good: AUTO_SAMPLE_SIZE and METHOD_OPT => 'FOR ALL COLUMNS SIZE AUTO'. Histograms describe a skewed column's distribution and are what let the optimiser distinguish a value appearing twice from one appearing two million times.

Bind peeking is Oracle's version of the parameter sensitivity problem: the optimiser peeks at the bind values on the first parse and may produce a plan that suits them and not the next set. Adaptive cursor sharing mitigates it by allowing several plans per statement, and SQL Plan Management with baselines pins a known-good plan.

Partitioning divides a table into physical pieces by range, list, hash or a composite. It gives partition pruning, partition-wise joins and instantaneous archival by dropping a partition. It is a separately licensed option on Enterprise Edition. It is included in 23ai Free for development. Check your licence before a production design depends on it.

Similarly, AWR and ASH reports require the Diagnostics Pack licence. Running awrrpt.sql on an unlicensed Enterprise instance is a licence event. Statspack is the free predecessor and is still available.

Laboratory exercise 4 - a measured improvement.

Load at least two million rows with a skewed distribution. Declare a baseline: five queries with p50, p95 and p99, plus buffer gets and the actual plan for each.

Apply techniques one at a time and re-measure: a composite B-tree chosen from the plan, a function-based index, a bitmap index on a warehouse-shaped table, gathering statistics with a histogram on the skewed column, and partitioning the fact table if your edition permits.

Then demonstrate bind peeking: a query with a bind variable executed first for a rare value and then a common one, with plans and timings captured both ways round.

Include one change that did not help.

Deliverable: the benchmark report with all percentiles at each step, DBMS_XPLAN output before and after, the bind peeking demonstration with all four measurements, and a statement of which features you used and their licence status.

-- ------------------------------------------------------------------
-- Plans: what it DID, not what it would do.
-- ------------------------------------------------------------------
ALTER SESSION SET STATISTICS_LEVEL = ALL;

SELECT /*+ GATHER_PLAN_STATISTICS */ c.name, SUM(l.quantity * l.unit_price)
FROM ord_owner.customer c
JOIN ord_owner.orders o ON o.customer_id = c.customer_id
JOIN ord_owner.order_line l ON l.order_id = o.order_id
WHERE o.ordered_at >= TIMESTAMP '2026-01-01 00:00:00 +00:00'
GROUP BY c.name;

SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY_CURSOR(NULL, NULL, 'ALLSTATS LAST'));
-- | Id | Operation          | Name   | Starts | E-Rows | A-Rows | Buffers |
-- |  2 |  TABLE ACCESS FULL | ORDERS |      1 |    500 |  1204K |   98447 |
--                                              ^^^^^^   ^^^^^^
-- E-Rows 500 against A-Rows 1,204,000. The optimiser is choosing on a
-- picture of a different table. Fix the ESTIMATE before the plan.

-- ------------------------------------------------------------------
-- Index types, each on the query it is for.
-- ------------------------------------------------------------------
CREATE INDEX ord_owner.ix_orders_cust_date
    ON ord_owner.orders (customer_id, ordered_at) TABLESPACE app_data;
--                       ^^^^^^^^^^^ equality first, range last.

-- Oracle does NOT store NULLs in a plain B-tree. So this cannot use
-- the index above, which surprises people every time:
--   SELECT * FROM orders WHERE customer_id IS NULL;
-- A composite index including a constant does store them:
CREATE INDEX ord_owner.ix_orders_cust_nulls
    ON ord_owner.orders (customer_id, 1);

-- Function-based: the only way to index an expression.
CREATE INDEX ord_owner.ix_customer_upper_name
    ON ord_owner.customer (UPPER(name));
SELECT * FROM ord_owner.customer WHERE UPPER(name) = 'ACME LTD';

-- BITMAP. Read the warning before using one.
CREATE BITMAP INDEX ord_owner.bix_sales_region
    ON ord_owner.fact_sales (region_id);
--
-- A bitmap per distinct value. Extremely compact on low-cardinality
-- columns, and several can be ANDed together to resolve a multi-column
-- predicate without touching the table.
--
-- NEVER ON AN OLTP TABLE. Updating ONE row locks the entire bitmap
-- segment, which covers many rows. Two concurrent updates to
-- different rows block each other. Warehouses: yes. Anything taking
-- concurrent DML: no.

-- ------------------------------------------------------------------
-- Statistics and histograms.
-- ------------------------------------------------------------------
BEGIN
  DBMS_STATS.GATHER_TABLE_STATS(
    ownname          => 'ORD_OWNER',
    tabname          => 'ORDERS',
    estimate_percent => DBMS_STATS.AUTO_SAMPLE_SIZE,
    method_opt       => 'FOR ALL COLUMNS SIZE AUTO',
    cascade          => TRUE,       -- indexes too
    degree           => 4);
END;
/

SELECT column_name, num_distinct, histogram, num_buckets, last_analyzed
FROM user_tab_col_statistics WHERE table_name = 'ORDERS';
-- A histogram on a skewed column is what lets the optimiser tell a
-- value appearing twice from one appearing two million times.

-- ------------------------------------------------------------------
-- BIND PEEKING - Oracle's parameter sensitivity.
-- ------------------------------------------------------------------
VARIABLE cust NUMBER;
EXEC :cust := 42;      -- 3 orders
SELECT COUNT(*) FROM ord_owner.orders WHERE customer_id = :cust;
-- plan: INDEX RANGE SCAN. Correct for 42.

EXEC :cust := 7;       -- 4,000,000 orders
SELECT COUNT(*) FROM ord_owner.orders WHERE customer_id = :cust;
-- SAME cursor, SAME plan, now badly wrong.

SELECT sql_id, child_number, is_bind_sensitive, is_bind_aware,
       executions, buffer_gets
FROM v$sql WHERE sql_text LIKE '%customer_id = :cust%';
-- Adaptive cursor sharing allows several plans per statement once it
-- notices. Or pin the good one with a SQL plan baseline:
--   DBMS_SPM.LOAD_PLANS_FROM_CURSOR_CACHE(sql_id => '...');

-- ------------------------------------------------------------------
-- PARTITIONING - a SEPARATELY LICENSED option on Enterprise Edition.
-- ------------------------------------------------------------------
CREATE TABLE ord_owner.orders_part (
    order_id    NUMBER(12),
    customer_id NUMBER(12) NOT NULL,
    ordered_at  DATE NOT NULL,
    total_amount NUMBER(19,4)
)
PARTITION BY RANGE (ordered_at)
INTERVAL (NUMTOYMINTERVAL(1,'MONTH'))     -- partitions created on demand
( PARTITION p_initial VALUES LESS THAN (DATE '2026-01-01') )
TABLESPACE app_data;

-- Pruning: the plan must show Pstart/Pstop naming ONE partition.
EXPLAIN PLAN FOR
SELECT COUNT(*) FROM ord_owner.orders_part
WHERE ordered_at >= DATE '2026-11-01' AND ordered_at < DATE '2026-12-01';
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY(NULL, NULL, 'BASIC +PARTITION'));

-- Retention in milliseconds rather than a DELETE that generates undo:
ALTER TABLE ord_owner.orders_part DROP PARTITION FOR (DATE '2025-01-01');

-- CHECK WHAT YOU ARE USING. This is a commercial question, not a
-- technical one, and it is discovered during an audit:
SELECT name, detected_usages, currently_used
FROM dba_feature_usage_statistics
WHERE name IN ('Partitioning (user)','Advanced Compression',
               'Real Application Clusters','Diagnostic Pack',
               'Tuning Pack','Active Data Guard')
  AND detected_usages > 0;
-- AWR and ASH reports require the Diagnostics Pack. Running awrrpt.sql
-- on an unlicensed Enterprise instance is itself a licence event.
-- Statspack is the free predecessor and still ships.

Discussion

No questions on this topic yet. Sign in to ask the first one.