Is ‘no_found_rows’ a silver bullet for WP_Query optimization when getting all posts of a certain type?

Your code will run five SQL queries in total.

When setting no_found_rows => true the first two queries

SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts WHERE 1=1 AND wp_posts.ID IN (1,49,63,249,72,95,259,207,183,225) AND wp_posts.post_type="post" AND (wp_posts.post_status="publish") ORDER BY wp_posts.post_date ASC LIMIT 0, 10

SELECT FOUND_ROWS()

will become a single query like

SELECT wp_posts.ID FROM wp_posts  WHERE 1=1  AND wp_posts.ID IN (1,49,63,249,72,95,259,207,183,225) AND wp_posts.post_type="post" AND (wp_posts.post_status="publish")  ORDER BY wp_posts.post_date ASC LIMIT 0, 10

so yes, no_found_rows will improve performance to some extent.

I don’t need any meta information, no paging information, no counting of the posts, nothing, just the raw posts

In this case, you can further optimize. WP_Query will cache taxonomies by default, but setting update_post_term_cache => false will skip the following query

SELECT t.*, tt.*, tr.object_id FROM wp_terms AS t INNER JOIN wp_term_taxonomy AS tt ON t.term_id = tt.term_id INNER JOIN wp_term_relationships AS tr ON tr.term_taxonomy_id = tt.term_taxonomy_id WHERE tt.taxonomy IN ('category', 'post_tag', 'post_format') AND tr.object_id IN (1, 49, 63, 72, 95, 183, 207, 225, 249, 259) ORDER BY t.name ASC

Likewise, setting update_post_meta_cache => false will avoid WP_Query caching posts metadata and will skip the following query

SELECT post_id, meta_key, meta_value FROM wp_postmeta WHERE post_id IN (1,49,63,72,95,183,207,225,249,259) ORDER BY meta_id ASC

So we can go from five (5) queries down to two (2) just setting these attributes.

Keep in mind that these optimzations can lead to N+1 problems if afterwards during the loop you actually attempt to display categorization information or any metadata such as post thumbnails, so use them wisely.

Leave a Comment