Speeding Up Post Queries With no_found_rows

Recently I stumbled upon an article that was written to highlight a flaw in the generalized way that WordPress is written. Amazingly, it was written over 3.5 years ago and still holds true today.

Any time you call the get_posts() or query_posts() function, WordPress is querying the database in such a way that it can easily implement pagination using the SQL_CALC_FOUND_ROWS functionality within MySQL. That’s great in theory, but it’s also slow and inefficient when you have a very large posts table. What if you know that the query you are generating will not trigger pagination? Why include all that overhead?

This is a classic example of software thinking it’s smarter than people; but fortunately, there is a workaround. Thanks to the undocumented variable no_found_rows you can tell get_posts() and query_posts() not to do this extra work with a simple boolean value.

It would be nice to see WordPress attempt to do this somewhat automatically. If numberposts is defined, as it is in the example above, WordPress could check to see if the requested number of results is less than the posts_per_page value. If pagination will not be needed, disable the SQL_CALC_FOUND_ROWS functionality automatically.

Seeing no_found_rows being documented in the Codex would be nice, since this information is not “news” anywhere. A quick Google search proves that people mention this frequently when discussing how to speed up WordPress. And perhaps a better name would be nice as well: the current variable speaks to the technical function it does (“do not use the SQL_CALC_FOUND_ROWS feature”), but why not uses_pagination or get_row_count?

Leave a Reply