Skip to content

Instantly share code, notes, and snippets.

@xtender
Created December 21, 2024 01:54
Show Gist options
  • Save xtender/54a415dff3d064a2e4ddddd53a328b0a to your computer and use it in GitHub Desktop.
Save xtender/54a415dff3d064a2e4ddddd53a328b0a to your computer and use it in GitHub Desktop.
Simple example of how smart is Oracle CBO with indexes like on dates(trunc(date_col))
SQL> create table dates(date_col, padding) as select date'2020-01-01' + level*5/24/60, level from dual connect by level<=10000;
SQL> create index ix_dates_trunc on dates(trunc(date_col));
SQL> exec dbms_stats.gather_table_stats('','DATES');
SQL> select min(date_col),max(date_col),count(*) from dates where date_col=to_date('2020-01-15 01:15','yyyy-mm-dd hh24:mi');
MIN(DATE_COL) MAX(DATE_COL) COUNT(*)
------------------- ------------------- ----------
2020-01-15 01:15:00 2020-01-15 01:15:00 1
SQL> select * from dbms_xplan.display_cursor('','','allstats last -projection -alias');
PLAN_TABLE_OUTPUT
-----------------------------------------------------------------------------------------------------------------
SQL_ID fd6supjf60v5q, child number 0
-------------------------------------
select min(date_col),max(date_col),count(*) from dates where
date_col=to_date('2020-01-15 01:15','yyyy-mm-dd hh24:mi')
Plan hash value: 3740522312
-----------------------------------------------------------------------------------------------------------------
| Id | Operation | Name | Starts | E-Rows | A-Rows | A-Time | Buffers |
-----------------------------------------------------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 1 | | 1 |00:00:00.01 | 5 |
| 1 | SORT AGGREGATE | | 1 | 1 | 1 |00:00:00.01 | 5 |
|* 2 | TABLE ACCESS BY INDEX ROWID BATCHED| DATES | 1 | 1 | 1 |00:00:00.01 | 5 |
|* 3 | INDEX RANGE SCAN | IX_DATES_TRUNC | 1 | 40 | 288 |00:00:00.01 | 3 |
-----------------------------------------------------------------------------------------------------------------
Predicate Information (identified by operation id):
---------------------------------------------------
2 - filter("DATE_COL"=TO_DATE(' 2020-01-15 01:15:00', 'syyyy-mm-dd hh24:mi:ss'))
3 - access("DATES"."SYS_NC00003$"=TRUNC(TO_DATE(' 2020-01-15 01:15:00', 'syyyy-mm-dd hh24:mi:ss')))
create table dates(date_col, padding) as select date'2020-01-01' + level*5/24/60, level from dual connect by level<=10000;
create index ix_dates_trunc on dates(trunc(date_col));
exec dbms_stats.gather_table_stats('','DATES');
select min(date_col),max(date_col),count(*) from dates where date_col=to_date('2020-01-15 01:15','yyyy-mm-dd hh24:mi');
select * from dbms_xplan.display_cursor('','','allstats last -projection -alias');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment