I’m running this query on an Oracle DB:
SELECT COUNT(1) FROM db.table WHERE columnA = 'VALUE' AND ROWNUM < 2
There is no index on columnA, and the table has many many thousands of lines (possibly millions). There’s about twenty values that should be returned, so it’s not a huge set being returned. However, because it triggers a full table scan it takes eons. How can I make it go faster?
Note: I’m not a DBA so I have limited access to the database and can’t implement restructuring, or adding indexes, or get rid of old data.
If you’re looking for the existence of a row, not the number of times it appears, then this would be more appropriate:
That will stop the query as fast as possible once a row’s been found; however, if you need it to go faster, that’s what indexes are for.
Test Case:
The data for column_A is well distributed, and can be found in the first few blocks for all values, so this query runs well:
Sub .1 sec execution time and low I/O – on the order of 4 I/Os. However, when looking for a value that’s NOT present, things change alarmingly:
20-40 seconds of execution time, and over 100,000 I/Os.
However, if we add the index:
We get sub .1 second response time and single-digit I/Os from both queries.