WordPress.org

Make WordPress Core

Opened 3 years ago

Last modified 3 months ago

#18836 new enhancement

ORDER BY RAND() is slow

Reported by: scribu Owned by:
Milestone: Awaiting Review Priority: normal
Severity: minor Version:
Component: Query Keywords: needs-patch
Focuses: performance Cc:

Description (last modified by scribu)

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.

Change History (6)

comment:1 scribu3 years ago

Here's a method of doing it all in a single query:

http://explainextended.com/2009/03/01/selecting-random-rows/

Not sure how feasible it would be for WP.

comment:2 sirzooro3 years ago

  • Cc sirzooro added

comment:3 scribu3 years ago

  • Description modified (diff)

comment:4 c3mdigital8 months ago

  • Keywords needs-patch added

comment:6 nacin3 months ago

  • Component changed from Performance to Query
  • Focuses performance added
Note: See TracTickets for help on using tickets.