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?
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 yourCOUNT(*). 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.