Mapi Mapi - 1 month ago 11
PHP Question

PHP: How can i select a random row from a MYSQL-Database?

i have a database-table "questions" on a online webserver with 2000+rows and i need to get 6 randomly selected rows (=questions")! they must be different so that one question is not two times in the list array of 6 questions.
How can i achieve this in a performant way?

Thank you so much!

Answer

You have a relatively small amount of data, so the simplest method is:

select q.*
from questions q
order by rand()
limit 6;

In this query, the order by takes the longest amount of time. Ordering 2,000 rows might be noticeable. A simple fix is to reduce the number of rows being ordered. One method is:

select q.*
from questions q cross join
     (select count(*) as cnt from questions) m
where rand() < 100 / m.cnt
order by rand()
limit 6;

The where selects about 100 rows randomly and then orders those to select 6. You are pretty much guaranteed that the where will always choose at least 6 rows.