Same Rows, Same Index, 50x the Work: Oracle's Clustering Factor

Categories: Oracle Database · Performance

This is a case I like to demo during my trainings: Two tables with the same rows, the same columns and the same index on the same column, with fresh stats on both. You run the same query against each one. On one table the optimizer uses the index and does 198 buffer gets. On the other it ignores the index and reads the whole table.

There is nothing broken here. The difference is one setting most DBAs never check: the clustering factor. I built both tables on my Oracle 19c lab (Enterprise Edition, 19.26), in a PDB with a schema called BLOG. The main demo ran as one script, and the extra tests later in the post ran right after it. All the output in this post is copied from those executions.

Building the two tables

The first table has 1 million orders for 5,000 customers, 200 orders each. Rows go in by order_id, so all the orders of one customer end up next to each other on disk. The second table is a copy of the first, with the rows inserted in random order.

exec dbms_random.seed(42)

create table orders_sorted as
with g as (select level n from dual connect by level <= 1000)
select rownum                                as order_id,
       ceil(rownum / 200)                    as cust_id,
       date '2025-01-01' + mod(rownum, 365)  as order_date,
       round(dbms_random.value(10, 1000), 2) as amount,
       rpad('x', 100, 'x')                   as padding
from g a, g b;

create table orders_shuffled as
select * from orders_sorted order by dbms_random.value;

create index orders_sorted_cust_ix   on orders_sorted(cust_id);
create index orders_shuffled_cust_ix on orders_shuffled(cust_id);

exec dbms_stats.gather_table_stats('BLOG', 'ORDERS_SORTED')
exec dbms_stats.gather_table_stats('BLOG', 'ORDERS_SHUFFLED')

Same data, same index, fresh stats. The only difference is where the rows landed inside the table blocks.

A side note on the connect by: my first try used connect by level <= 1000000 and failed with ORA-30009: Not enough memory for CONNECT BY operation. My lab doesn’t have much PGA. Joining two 1,000-row generators gives you the same million rows without the memory problem.

The number that tells them apart

select t.table_name, t.num_rows, t.blocks,
       i.index_name, i.distinct_keys, i.clustering_factor
from   all_tables t
join   all_indexes i on i.table_owner = t.owner and i.table_name = t.table_name
where  t.owner = 'BLOG'
order  by t.table_name;
TABLE_NAME         NUM_ROWS     BLOCKS INDEX_NAME               DISTINCT_KEYS CLUSTERING_FACTOR
---------------- ---------- ---------- ------------------------ ------------- -----------------
ORDERS_SHUFFLED     1000000      18033 ORDERS_SHUFFLED_CUST_IX           5000            994580
ORDERS_SORTED       1000000      18025 ORDERS_SORTED_CUST_IX             5000             17850

Walk the whole index from start to end and count every time you have to jump to a different table block. That count is the clustering factor. It sits between two limits:

  • Close to the number of blocks (18,025 here) means rows with the same key live together. One block read brings back a lot of the rows you want.
  • Close to the number of rows (1,000,000 here) means almost every index entry sends you to a different block than the one before it.

The sorted table is at the best end. The shuffled one is close to the worst end. The script starts with dbms_random.seed(42), so every rebuild gives exactly the same two tables, with a clustering factor of 994,580 for the shuffled one. I needed that for a test later in this post.

Same query, two different plans

I ask for the orders of 50 customers. That’s 10,000 rows, or 1% of the table. With statistics_level = all, ALLSTATS LAST shows the real row counts and buffer gets of the last execution. I only show the plan table from each DBMS_XPLAN output.

alter session set statistics_level = all;

select sum(amount) from orders_sorted where cust_id between 1 and 50;
select * from table(dbms_xplan.display_cursor(format => 'ALLSTATS LAST +COST'));
-------------------------------------------------------------------------------------------------------------------------------------
| Id  | Operation                            | Name                  | Starts | E-Rows | Cost (%CPU)| A-Rows |   A-Time   | Buffers |
-------------------------------------------------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT                     |                       |      1 |        |   202 (100)|      1 |00:00:00.01 |     198 |
|   1 |  SORT AGGREGATE                      |                       |      1 |      1 |            |      1 |00:00:00.01 |     198 |
|   2 |   TABLE ACCESS BY INDEX ROWID BATCHED| ORDERS_SORTED         |      1 |  10002 |   202   (0)|  10000 |00:00:00.01 |     198 |
|*  3 |    INDEX RANGE SCAN                  | ORDERS_SORTED_CUST_IX |      1 |  10002 |    23   (0)|  10000 |00:00:00.01 |      22 |
-------------------------------------------------------------------------------------------------------------------------------------

The sorted table uses the index and reads 198 buffers to get 10,000 rows. Now the same query on the shuffled table:

select sum(amount) from orders_shuffled where cust_id between 1 and 50;
select * from table(dbms_xplan.display_cursor(format => 'ALLSTATS LAST +COST'));
-------------------------------------------------------------------------------------------------------------
| Id  | Operation          | Name            | Starts | E-Rows | Cost (%CPU)| A-Rows |   A-Time   | Buffers |
-------------------------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT   |                 |      1 |        |  4900 (100)|      1 |00:00:00.05 |   17868 |
|   1 |  SORT AGGREGATE    |                 |      1 |      1 |            |      1 |00:00:00.05 |   17868 |
|*  2 |   TABLE ACCESS FULL| ORDERS_SHUFFLED |      1 |  10002 |  4900   (1)|  10000 |00:00:00.05 |   17868 |
-------------------------------------------------------------------------------------------------------------

Same index, same 10,000 rows, and the optimizer goes for a full table scan: 17,868 buffers.

Why? Look at the cost. The index part costs 23 for both tables. For the table part, Oracle uses roughly the clustering factor times the fraction of rows you want. On the sorted table that is 17,850 × 1% ≈ 179, and 23 + 179 gives the 202 you see in the plan. On the shuffled table it is 994,580 × 1% ≈ 9,946. The full scan costs 4,900. So the full scan wins.

Forcing the index on the shuffled table

select /*+ index(o orders_shuffled_cust_ix) */ sum(amount)
from   orders_shuffled o
where  cust_id between 1 and 50;
select * from table(dbms_xplan.display_cursor(format => 'ALLSTATS LAST +COST'));
---------------------------------------------------------------------------------------------------------------------------------------
| Id  | Operation                            | Name                    | Starts | E-Rows | Cost (%CPU)| A-Rows |   A-Time   | Buffers |
---------------------------------------------------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT                     |                         |      1 |        |  9974 (100)|      1 |00:00:00.01 |    9966 |
|   1 |  SORT AGGREGATE                      |                         |      1 |      1 |            |      1 |00:00:00.01 |    9966 |
|   2 |   TABLE ACCESS BY INDEX ROWID BATCHED| ORDERS_SHUFFLED         |      1 |  10002 |  9974   (1)|  10000 |00:00:00.01 |    9966 |
|*  3 |    INDEX RANGE SCAN                  | ORDERS_SHUFFLED_CUST_IX |      1 |  10002 |    23   (0)|  10000 |00:00:00.01 |      22 |
---------------------------------------------------------------------------------------------------------------------------------------

Same plan shape as the sorted table, same index, same 10,000 rows. 9,966 buffers here against 198 on the sorted table, about 50 times the work. The index part is the same on both (22 buffers). All the extra work is in the table, jumping from block to block. The cost of 9,974 is close to the math above: about 9,946 for the table plus 23 for the index.

Was the optimizer right to skip the index? On my lab, no. The forced index took 0.01 seconds, and the full scan took 0.05. Both ran with everything already in the buffer cache, so I flushed the cache and ran both again. alter system flush buffer_cache needs the ALTER SYSTEM privilege, and you should only run it on a test box.

NAME                                 TYPE        VALUE
------------------------------------ ----------- ------------------------------
filesystemio_options                 string      none
alter system flush buffer_cache;
select sum(amount) from orders_shuffled where cust_id between 1 and 50;
select * from table(dbms_xplan.display_cursor(format => 'ALLSTATS LAST'));
---------------------------------------------------------------------------------------------------------
| Id  | Operation          | Name            | Starts | E-Rows | A-Rows |   A-Time   | Buffers | Reads  |
---------------------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT   |                 |      1 |        |      1 |00:00:00.13 |   17868 |  17859 |
|   1 |  SORT AGGREGATE    |                 |      1 |      1 |      1 |00:00:00.13 |   17868 |  17859 |
|*  2 |   TABLE ACCESS FULL| ORDERS_SHUFFLED |      1 |  10002 |  10000 |00:00:00.13 |   17868 |  17859 |
---------------------------------------------------------------------------------------------------------
alter system flush buffer_cache;
select /*+ index(o orders_shuffled_cust_ix) */ sum(amount)
from   orders_shuffled o
where  cust_id between 1 and 50;
select * from table(dbms_xplan.display_cursor(format => 'ALLSTATS LAST'));
-----------------------------------------------------------------------------------------------------------------------------------
| Id  | Operation                            | Name                    | Starts | E-Rows | A-Rows |   A-Time   | Buffers | Reads  |
-----------------------------------------------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT                     |                         |      1 |        |      1 |00:00:00.06 |    9966 |   7776 |
|   1 |  SORT AGGREGATE                      |                         |      1 |      1 |      1 |00:00:00.06 |    9966 |   7776 |
|   2 |   TABLE ACCESS BY INDEX ROWID BATCHED| ORDERS_SHUFFLED         |      1 |  10002 |  10000 |00:00:00.06 |    9966 |   7776 |
|*  3 |    INDEX RANGE SCAN                  | ORDERS_SHUFFLED_CUST_IX |      1 |  10002 |  10000 |00:00:00.01 |      22 |     40 |
-----------------------------------------------------------------------------------------------------------------------------------

From a cold cache, the full scan took 0.13 seconds with 17,859 reads, and the forced index took 0.06 seconds with 7,776 reads. The index still won. My lab runs with filesystemio_options = none, so Oracle’s “physical” reads go through the Linux page cache, and flushing the buffer cache doesn’t empty that one. The optimizer’s cost model knows nothing about the page cache. It counts every one of those table block reads as a real disk read. So this “cold” test isn’t really cold. To see what happens when the reads really go to disk, I ran it again with filesystemio_options = setall.

Running it again without the Linux page cache

setall turns on both direct I/O and asynchronous I/O for the datafiles. With direct I/O, Oracle opens them with O_DIRECT, and its reads skip the Linux page cache. The parameter is static, so it needs a restart:

alter system set filesystemio_options = setall scope = spfile;
shutdown immediate
startup

Before the restart I rebuilt the two tables with the same script. Thanks to the seed they came out identical, and the stats after the restart show the same clustering factor:

TABLE_NAME         NUM_ROWS     BLOCKS INDEX_NAME               DISTINCT_KEYS CLUSTERING_FACTOR
---------------- ---------- ---------- ------------------------ ------------- -----------------
ORDERS_SHUFFLED     1000000      18033 ORDERS_SHUFFLED_CUST_IX           5000            994580
ORDERS_SORTED       1000000      18025 ORDERS_SORTED_CUST_IX             5000             17850
NAME                                 TYPE        VALUE
------------------------------------ ----------- ------------------------------
filesystemio_options                 string      SETALL

To be sure the setting really took effect, I looked at the open flags of the BLOG_DATA datafile in /proc/<pid>/fdinfo for the DBWR process. They went from 02110002 before the restart to 02150002 after it. The difference is 040000, which is O_DIRECT.

Then I ran the same two cold queries, with the same flush before each one:

---------------------------------------------------------------------------------------------------------
| Id  | Operation          | Name            | Starts | E-Rows | A-Rows |   A-Time   | Buffers | Reads  |
---------------------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT   |                 |      1 |        |      1 |00:00:00.25 |   17861 |  17859 |
|   1 |  SORT AGGREGATE    |                 |      1 |      1 |      1 |00:00:00.25 |   17861 |  17859 |
|*  2 |   TABLE ACCESS FULL| ORDERS_SHUFFLED |      1 |  10002 |  10000 |00:00:00.24 |   17861 |  17859 |
---------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------
| Id  | Operation                            | Name                    | Starts | E-Rows | A-Rows |   A-Time   | Buffers | Reads  |
-----------------------------------------------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT                     |                         |      1 |        |      1 |00:00:00.46 |    9966 |   7750 |
|   1 |  SORT AGGREGATE                      |                         |      1 |      1 |      1 |00:00:00.46 |    9966 |   7750 |
|   2 |   TABLE ACCESS BY INDEX ROWID BATCHED| ORDERS_SHUFFLED         |      1 |  10002 |  10000 |00:00:00.46 |    9966 |   7750 |
|*  3 |    INDEX RANGE SCAN                  | ORDERS_SHUFFLED_CUST_IX |      1 |  10002 |  10000 |00:00:00.04 |      22 |     22 |
-----------------------------------------------------------------------------------------------------------------------------------

Now the full scan wins: 0.25 seconds against 0.46 for the forced index. The buffer gets are the same as before, but none of the 7,750 reads can come from the Linux page cache anymore.

One run can be noise, so I ran the pair three more times. Then I set filesystemio_options back to none, restarted again and ran the same three rounds:

filesystemio_options Run Full scan Forced index
none first cold test above 0.13 s 0.06 s
setall first run after restart 0.25 s 0.46 s
setall three more runs 0.28 s, 0.28 s, 0.27 s 0.37 s, 0.36 s, 0.38 s
none three runs after restarting back 0.56 s, 0.25 s, 0.31 s 3.26 s, 2.99 s, 0.06 s

With setall, the full scan won every time. With real reads, the optimizer was right to skip the index.

Look at the last row. Same table, same plans, same setting as the first cold test, and the forced index took about 3 seconds twice before it dropped back to 0.06. This box has about 7.5 GB of RAM and 6 GB goes to the SGA, so the Linux page cache gets less than 1 GB (780 MB when I checked), and what’s in it changes all the time. I didn’t trace those slow runs, so I won’t guess at the exact reason. What it does show is that with none, your timings depend on what Linux happens to have cached at that moment.

The index loses quickly when you ask for more rows. Here are the same two plans for 500 customers (100,000 rows, 10% of the table), each run after a fresh flush:

alter system flush buffer_cache;
select /*+ index(o orders_shuffled_cust_ix) */ sum(amount)
from   orders_shuffled o
where  cust_id between 1 and 500;
select * from table(dbms_xplan.display_cursor(format => 'ALLSTATS LAST'));
-----------------------------------------------------------------------------------------------------------------------------------
| Id  | Operation                            | Name                    | Starts | E-Rows | A-Rows |   A-Time   | Buffers | Reads  |
-----------------------------------------------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT                     |                         |      1 |        |      1 |00:00:00.25 |   99358 |  18038 |
|   1 |  SORT AGGREGATE                      |                         |      1 |      1 |      1 |00:00:00.25 |   99358 |  18038 |
|   2 |   TABLE ACCESS BY INDEX ROWID BATCHED| ORDERS_SHUFFLED         |      1 |    100K|    100K|00:00:00.24 |   99358 |  18038 |
|*  3 |    INDEX RANGE SCAN                  | ORDERS_SHUFFLED_CUST_IX |      1 |    100K|    100K|00:00:00.02 |     209 |    232 |
-----------------------------------------------------------------------------------------------------------------------------------
alter system flush buffer_cache;
select /*+ full(o) */ sum(amount)
from   orders_shuffled o
where  cust_id between 1 and 500;
select * from table(dbms_xplan.display_cursor(format => 'ALLSTATS LAST'));
---------------------------------------------------------------------------------------------------------
| Id  | Operation          | Name            | Starts | E-Rows | A-Rows |   A-Time   | Buffers | Reads  |
---------------------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT   |                 |      1 |        |      1 |00:00:00.14 |   17868 |  17859 |
|   1 |  SORT AGGREGATE    |                 |      1 |      1 |      1 |00:00:00.14 |   17868 |  17859 |
|*  2 |   TABLE ACCESS FULL| ORDERS_SHUFFLED |      1 |    100K|    100K|00:00:00.13 |   17868 |  17859 |
---------------------------------------------------------------------------------------------------------

The index path did 99,358 buffer gets and 18,038 reads in 0.25 seconds. That’s about as many reads as the whole table has blocks (18,033), and more than five times the buffer gets of the full scan. The full scan read the table once, 17,868 buffers in 0.14 seconds. With setall the gap was bigger: I ran the same pair there too, and the index took 1.09 seconds against 0.40 for the full scan.

The fix: put the rows back in order

A new index won’t help here, and a hint only forces the expensive path you just saw. You have to fix the table. On 19c Enterprise Edition you can add attribute clustering and then move the table online, so DML can keep running while it moves:

alter table orders_shuffled add clustering by linear order (cust_id);
alter table orders_shuffled move online;
Table altered.

Elapsed: 00:00:00.06

Table altered.

Elapsed: 00:00:10.80
select index_name, status from all_indexes
where  owner = 'BLOG' and table_name = 'ORDERS_SHUFFLED';
INDEX_NAME               STATUS
------------------------ --------
ORDERS_SHUFFLED_CUST_IX  VALID

The move took 10.8 seconds, and the index was still VALID afterwards. After new stats, the clustering factor of the shuffled table went from 994,580 down to 17,850, the same as the sorted table:

exec dbms_stats.gather_table_stats('BLOG', 'ORDERS_SHUFFLED')
TABLE_NAME         NUM_ROWS     BLOCKS INDEX_NAME               DISTINCT_KEYS CLUSTERING_FACTOR
---------------- ---------- ---------- ------------------------ ------------- -----------------
ORDERS_SHUFFLED     1000000      18025 ORDERS_SHUFFLED_CUST_IX           5000             17850
ORDERS_SORTED       1000000      18025 ORDERS_SORTED_CUST_IX             5000             17850

Same query again, no hint:

select sum(amount) from orders_shuffled where cust_id between 1 and 50;
select * from table(dbms_xplan.display_cursor(format => 'ALLSTATS LAST +COST'));
---------------------------------------------------------------------------------------------------------------------------------------
| Id  | Operation                            | Name                    | Starts | E-Rows | Cost (%CPU)| A-Rows |   A-Time   | Buffers |
---------------------------------------------------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT                     |                         |      1 |        |   202 (100)|      1 |00:00:00.01 |     198 |
|   1 |  SORT AGGREGATE                      |                         |      1 |      1 |            |      1 |00:00:00.01 |     198 |
|   2 |   TABLE ACCESS BY INDEX ROWID BATCHED| ORDERS_SHUFFLED         |      1 |  10002 |   202   (0)|  10000 |00:00:00.01 |     198 |
|*  3 |    INDEX RANGE SCAN                  | ORDERS_SHUFFLED_CUST_IX |      1 |  10002 |    23   (0)|  10000 |00:00:00.01 |      22 |
---------------------------------------------------------------------------------------------------------------------------------------

The optimizer picks the index on its own again, and the query reads 198 buffers instead of 17,868.

This one got me. After the fix I ran the queries again, and the “shuffled” table used the index and read 199 buffers. It took me a moment to see why: after this step ORDERS_SHUFFLED isn’t shuffled anymore. If you want to repeat the demo, drop and rebuild the table first.

One more catch. Oracle only applies the clustering when data is loaded with direct-path inserts or moved. Normal INSERTs ignore it, so on a busy table the clustering factor creeps back up over time, and you’ll need a move every now and then.

Finding bad clustering factors in your own database

This query lists the indexes whose clustering factor is close to the number of rows:

select i.owner, i.table_name, i.index_name,
       t.blocks, t.num_rows, i.clustering_factor,
       round(i.clustering_factor / nullif(t.num_rows, 0) * 100) as pct_of_rows
from   dba_indexes i
join   dba_tables  t on t.owner = i.table_owner and t.table_name = i.table_name
where  i.owner not in (select username from dba_users where oracle_maintained = 'Y')
and    t.num_rows > 100000
and    i.clustering_factor > t.blocks * 10
order  by pct_of_rows desc
fetch first 10 rows only;

I ran it on the Swingbench schema in another PDB of the same lab:

OWNER  TABLE_NAME    INDEX_NAME                   BLOCKS   NUM_ROWS CLUSTERING_FACTOR PCT_OF_ROWS
------ ------------- ------------------------ ---------- ---------- ----------------- -----------
SOE    ADDRESSES     ADDRESS_PK                   378635   32681424          32681364         100
SOE    CARD_DETAILS  CARD_DETAILS_PK              199001   25923545          25923539         100
SOE    CUSTOMERS     CUST_FUNC_LOWER_NAME_IX      389660   21023544          21021734         100
SOE    CUSTOMERS     CUST_EMAIL_IX                389660   21023544          21023124         100
SOE    ORDERS        ORDER_PK                     703587   43920314          43920312         100
SOE    CUSTOMERS     CUSTOMERS_PK                 389660   21023544          21023539         100
SOE    ORDERS        ORD_ORDER_DATE_IX            703587   43920314          43919066         100
SOE    ORDERS        ORD_CUSTOMER_IX              703587   43920314          43920177         100
SOE    ORDERS        ORD_SALES_REP_IX             703587   43920314          43920195         100
SOE    CUSTOMERS     CUST_DOB_IX                  389660   21023544          20988514         100

Every index in the list is at 100%, primary keys included. So don’t assume your own indexes look better. Run the query and see.

Before you start moving tables:

  • A table can only be sorted one way. If you cluster ORDERS by cust_id, an index on order_date gets worse. Pick the column your most important range scans use.
  • A bad clustering factor hurts index range scans that return many rows. A primary key lookup for one row doesn’t care.
  • On tables where many sessions insert at the same time, the default statistic can make the clustering factor look worse than it really is. Look at the TABLE_CACHED_BLOCKS preference of DBMS_STATS before you rebuild anything. I didn’t test it here.

Next time someone tells you Oracle is “ignoring the index for no reason”, check the clustering factor before you reach for a hint.

Comments