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?
I don't have the points to comment, so I am posting this as an answer...
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".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
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