Cost-Based Optimizer & Execution Plan Mastery

Cost-Based Optimizer & Execution Plan Mastery in Oracle Database: The Cost-Based Optimizer (CBO) evaluates thousands of execution permutations (access paths,…

The Cost-Based Optimizer (CBO) evaluates thousands of execution permutations (access paths, join orders, join algorithms) for every query and picks the path with the lowest calculated Cost (an estimate of CPU cycles and I/O operations).


Gathering Optimizer Statistics

The optimizer makes correct decisions only when it has accurate data dictionary statistics. If statistics are stale, the CBO assumes outdated table cardinalities and chooses poor join algorithms:

-- Gather statistics on a table, including all indexes and column histograms
BEGIN
    DBMS_STATS.GATHER_TABLE_STATS(
        ownname          => 'PROD_APP',
        tabname          => 'TRANSACTIONS',
        cascade          => TRUE,        -- Gathers index stats simultaneously
        estimate_percent => DBMS_STATS.AUTO_SAMPLE_SIZE,
        method_opt       => 'FOR ALL COLUMNS SIZE AUTO' -- Builds histograms on skewed columns
    );
END;
/

Generating and Reading Execution Plans

Use EXPLAIN PLAN FOR and Oracle's standard diagnostics package DBMS_XPLAN:

-- Step 1: Explain the query
EXPLAIN PLAN FOR
SELECT 
    c.organization,
    SUM(o.order_total) AS total_spent
FROM corporate_accounts c
JOIN customer_orders o ON c.account_id = o.customer_id
WHERE c.status = 'ACTIVE' AND o.order_date >= TO_DATE('2024-01-01', 'YYYY-MM-DD')
GROUP BY c.organization;

-- Step 2: Format and display the plan output
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY(format => 'ALL'));

Anatomical Breakdown of Execution Plan Output

Plan hash value: 2490184512

------------------------------------------------------------------------------------------------------
| Id  | Operation                     | Name                 | Rows  | Bytes | Cost (%CPU)| Time     |
------------------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT              |                      |   150 |  6450 |    42   (3)| 00:00:01 |
|   1 |  HASH GROUP BY                |                      |   150 |  6450 |    42   (3)| 00:00:01 |
|*  2 |   HASH JOIN                   |                      |  1200 | 51600 |    41   (0)| 00:00:01 |
|*  3 |    TABLE ACCESS BY INDEX ROWID| CORPORATE_ACCOUNTS   |   300 |  6900 |     5   (0)| 00:00:01 |
|*  4 |     INDEX RANGE SCAN          | IDX_CORP_STATUS      |   300 |       |     2   (0)| 00:00:01 |
|*  5 |    TABLE ACCESS BY INDEX ROWID| CUSTOMER_ORDERS      |  4000 | 80000 |    36   (0)| 00:00:01 |
|*  6 |     INDEX RANGE SCAN          | IDX_ORDERS_DATE      |  4000 |       |     8   (0)| 00:00:01 |
------------------------------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------
   2 - access("C"."ACCOUNT_ID"="O"."CUSTOMER_ID")
   4 - access("C"."STATUS"='ACTIVE')
   6 - access("O"."ORDER_DATE">=TO_DATE('2024-01-01 00:00:00', 'yyyy-mm-dd hh24:mi:ss'))

How to Read the Hierarchy

  1. Read from the innermost indentation outwards, and top-to-bottom for sibling operations.
  2. Operation 4 (INDEX RANGE SCAN) runs first, returning row pointers to Operation 3 (TABLE ACCESS BY INDEX ROWID).
  3. Sibling Operation 6 runs, feeding Operation 5.
  4. Operation 2 joins the two datasets using a HASH JOIN.
  5. Operation 1 performs the group aggregation in PGA memory.

Warning Signs in Execution Plans

  • TABLE ACCESS FULL on Multi-Million Row Tables: Indicates a missing index or an unindexed function wrapping the column filter.
  • Cartesian Joins (MERGE JOIN CARTESIAN): Indicates a missing join predicate; causes exponential data blowups.
  • High Cost Discrepancy between Estimated Rows vs Actual Rows: Indicates stale statistics.

Exercises

  1. Generate and explain an execution plan for a 3-table join.
  2. Explain the difference between an INDEX RANGE SCAN, INDEX UNIQUE SCAN, and INDEX FAST FULL SCAN.
  3. Use an optimizer hint (/*+ LEADING(c) USE_HASH(o) */) to evaluate the cost difference between join strategies.