Friday, November 23, 2012

Oracle DB: count rows in a table

select COUNT(*) from WLI_REPORTING_ARCHIVE;
1513854

TECHNICALMESSAGEID can be null, and there is an INDEX on it:
select COUNT(TECHNICALMESSAGEID ) from WLI_REPORTING_ARCHIVE;
1513824
The difference is 30
select COUNT(*) from WLI_REPORTING_ARCHIVE where TECHNICALMESSAGEID is NULL;
30

of course
select COUNT(TECHNICALMESSAGEID) from WLI_REPORTING_ARCHIVE where TECHNICALMESSAGEID is null;
will immediately return 0
(it's very fast because probably the index keeps track of NULL entries)

This is not very accurate

SELECT NUM_ROWS FROM USER_TABLES WHERE TABLE_NAME = 'WLI_REPORTING_ARCHIVE';

unless the table has just been analyzed

This is VERY inaccurate
SELECT NUM_ROWS FROM USER_TABLES WHERE TABLE_NAME = 'WLI_REPORTING_ARCHIVE';

This is very accurate and fast
SELECT COUNT(*) * 100 FROM WLI_REPORTING_ARCHIVE SAMPLE (1);

explain plan for select COUNT(*) from WLI_REPORTING_ARCHIVE;

select * from table(dbms_xplan.display);

-----------------------------------------------------------------------------------------------
| Id  | Operation             | Name                          | Rows  | Cost (%CPU)| Time     |
-----------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT      |                               |     1 |  2921   (1)| 00:00:36 |
|   1 |  SORT AGGREGATE       |                               |     1 |            |          |
|   2 |   INDEX FAST FULL SCAN| WLI_REP_ARCHIVE_INDEX1 |  1499K|  2921   (1)| 00:00:36 |
-----------------------------------------------------------------------------------------------





see http://stackoverflow.com/questions/1840538/faster-alternative-in-oracle-to-select-count-from-sometable

No comments: