Jump to content

Optimize count query


Scooby08

Recommended Posts

I have a query that seems to lag a bit and although I'm not entirely sure the issue is this query, but it's a starting point..

 

SELECT count(*) FROM posts WHERE created >= DATE_SUB(NOW(), INTERVAL 1 DAY)

 

Is there any way to optimize this query any further? I have an index on the column "created" and the created date is in the following format "2012-07-13".

 

When running the query I get a count of 43551, but when I run an explain it says the following..

id select_type table type possible_keys key key_len ref rows Extra

1 SIMPLE posts range created created 13 NULL 251907 Using where; Using index

 

I've also tried the following variations for the heck of it, but they all come up the same..

 

SELECT count(*) FROM posts WHERE created BETWEEN (NOW() - INTERVAL 1 DAY) AND NOW()

SELECT count(*) FROM posts WHERE created BETWEEN DATE_SUB(NOW(), INTERVAL 1 DAY) AND NOW()

 

Any ideas??

Link to comment
https://forums.phpfreaks.com/topic/265635-optimize-count-query/
Share on other sites

I ended up using the following:

 

SELECT count(id) FROM posts WHERE (created BETWEEN (NOW() - INTERVAL 1 DAY) AND NOW())

 

Changing count(*) to count(id) did help to speed it up a bit, but my overall issue ended up being in the surrounding code outside of that query.. There's about 2,500,000 rows of data and now it's quick as can be and is not lagging in any way..

 

Thanks to all!

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.