[wp-trac] [WordPress Trac] #18836: ORDER BY RAND() is slow
WordPress Trac
wp-trac at lists.automattic.com
Sat Oct 1 17:43:48 UTC 2011
#18836: ORDER BY RAND() is slow
-------------------------+------------------------------
Reporter: scribu | Owner:
Type: enhancement | Status: new
Priority: normal | Milestone: Awaiting Review
Component: Performance | Version:
Severity: minor | Resolution:
Keywords: |
-------------------------+------------------------------
Description changed by scribu:
Old description:
> 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.
New description:
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 more than one post, we can get them in any order and
then call shuffle() on the resulting array.
--
--
Ticket URL: <http://core.trac.wordpress.org/ticket/18836#comment:3>
WordPress Trac <http://core.trac.wordpress.org/>
WordPress blogging software
More information about the wp-trac
mailing list