Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql upper limit for count(*)

I've got a query:

select count(*) from `table` where `something`>123

If the table has few million records, the query runs really slow even though there's an index on column something. However, in fact I'm interested in value of:

min(100000, count(*))

So is there any way to prevent MySQL from counting rows when it already found 100k? I've found something like:

select count(*) from (select 1 from `table` where `something`>123 limit 100000) as `asd`

It's much faster than count(*) if the table has a few million matching entries, but count(*) runs much faster when there are less than 100000 matches.

Is there any way to do it faster?

like image 333
Sebastian Nowak Avatar asked Dec 12 '11 17:12

Sebastian Nowak


1 Answers

I don't have the points to comment, so I am posting this as an answer...

  1. Have you tried using EXPLAIN to see if your index on something is actually being used? It sounds like this query is doing a Table Scan. Ideally, you will want to see something like "Extra: Using where; Using index".
  2. Out of curiosity, is something a nullable field?

As an aside, perhaps the query optimizer would do better with the following:

select count(*) as cnt
from table
where something > 123
having count(*) > 100000
like image 147
gangreen Avatar answered Oct 06 '22 05:10

gangreen