I've notice that in Oracle, the query
SELECT COUNT(*) FROM sometable;
is very slow for large tables. It seems like the database it actually going through every row and incrementing a counter one at a time. I would think that there would be a counter somewhere in the table how many rows that table has.
So if I want to check the number of rows in a table in Oracle, what is the fastest way to do that?
If you want just a rough estimate, you can extrapolate from a sample:
SELECT COUNT(*) * 100 FROM sometable SAMPLE (1);
For greater speed (but lower accuracy) you can reduce the sample size:
SELECT COUNT(*) * 1000 FROM sometable SAMPLE (0.1);
For even greater speed (but even worse accuracy) you can use block-wise sampling:
SELECT COUNT(*) * 100 FROM sometable SAMPLE BLOCK (1);
This works great for large tables.
SELECT NUM_ROWS FROM ALL_TABLES WHERE TABLE_NAME = 'TABLE_NAME_IN_UPPERCASE';
For small to medium size tables, following will be ok.
SELECT COUNT(Primary_Key) FROM table_name;
Cheers,
Think about it: the database really has to go to every row to do that. In a multi-user environment my COUNT(*)
could be different from your COUNT(*)
. It would be impractical to have a different counter for each and every session so you have literally to count the rows. Most of the time anyway you would have a WHERE clause or a JOIN in your query so your hypothetical counter would be of litte practical value.
There are ways to speed up things however: if you have an INDEX on a NOT NULL column Oracle will count the rows of the index instead of the table. In a proper relational model all tables have a primary key so the COUNT(*)
will use the index of the primary key.
Bitmap index have entries for NULL rows so a COUNT(*) will use a bitmap index if there is one available.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With