3

I have a database table questions on a online web server with 2000+ rows and I need to get 6 randomly selected rows. They must be different so that one question is not two times in the list array of 6 questions.

How can I achieve this?

4
  • 1
    select * from table order by rand() limit 6 ? Commented Oct 22, 2016 at 12:13
  • use your query with RAND() LIMIT 10; Commented Oct 22, 2016 at 12:13
  • But there is possibility some question to match another. Commented Oct 22, 2016 at 12:13
  • Possible duplicate of Fast random row in MySql Commented Oct 22, 2016 at 17:41

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

4

Use the DISTINCT operator in MySQL:

SELECT DISTINCT column FROM table ORDER BY RAND() LIMIT 6;

So DISTINCT will take care and remove duplicates

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.