Oracle FAQ | Your Portal to the Oracle Knowledge Grid |
Home -> Community -> Usenet -> c.d.o.server -> Re: What's fast way to get total of records
> I rather doubt there is one for Oracle. If there is a primary key or > otherwise not null index, it could be used in the count(*) and make > it faster than a table scan.
I created a test case to see if Oracle would use an index to count the number of records, and it seems that we need to give a hint, otherwise it just uses a FTS. Note that I use CBO on 9.2:
Oracle9i Enterprise Edition Release 9.2.0.1.0 - Production With the Partitioning, OLAP and Oracle Data Mining options JServer Release 9.2.0.1.0 - Production
SQL> create table tst (x char(1));
Table created.
Elapsed: 00:00:01.02
SQL> set timing off
SQL> truncate table plan_table;
Table truncated.
SQL> explain plan for
2 select count(*) from tst;
Explained.
SQL> select * from table(dbms_xplan.display);
PLAN_TABLE_OUTPUT
8 rows selected.
SQL> alter table tst add primary key(x);
Table altered.
SQL> truncate table plan_table;
Table truncated.
SQL> explain plan for
2 select count(*) from tst;
Explained.
SQL> select * from table(dbms_xplan.display);
PLAN_TABLE_OUTPUT
8 rows selected.
SQL> truncate table plan_table;
Table truncated.
SQL> select index_name from user_indexes where table_name = 'TST';
INDEX_NAME
Explained.
SQL> select * from table(dbms_xplan.display);
PLAN_TABLE_OUTPUT
8 rows selected.
Therefore, if you have an index on non-null field (such as a one associated to a PK), it's probably faster to include it in a hint as I did, in order to replace the FTS by an index full scan. Note also that presumably the "sort aggregate" step would be avoided if the index is defined as unique (I didn't test that).
Daniel Received on Fri Sep 26 2003 - 09:03:08 CDT