Make WordPress Core

Opened 7 years ago

Last modified 3 years ago

#18836 new enhancement

ORDER BY RAND() is slow — at Initial Version

Reported by: scribu Owned by:
Milestone: Future Release Priority: normal
Severity: minor Version:
Component: Query Keywords: needs-unit-tests has-patch needs-testing
Focuses: performance Cc:


WP_Query currently accepts 'orderby' => 'rand' which translates to ORDER BY RAND().

This is very slow when you have many posts, since it effectively calls RAND() for each row.

A faster way would be to call RAND() only once and put it in the LIMIT clause.

The only thing is that we have to make sure that the generated number is smaller than (total number of posts - number of posts to fetch).

So, this would require to do an extra query to calculate the total. It should still be faster than the current method.

If we want to get all the posts, we can get them in any order and then randomise their order using shuffle() in PHP.

Change History (0)

Note: See TracTickets for help on using tickets.