17

Possible Duplicate:
Selecting Random Rows in MySQL

I'm creating a simple web application using PHP and MySQL. In it, I need to randomly select a small set of rows from a table in a random order. How can I achieve such thing using MySQL?

2

3 Answers 3

47
SELECT * FROM table ORDER BY RAND() LIMIT 10;

Edit:

Useful information about the MySQL RAND() function can be found here.

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

5 Comments

Ouch... I've got > 500M rows! That's a bit slow...
There are other performant options, if you have a sequential primary key, precompute a range of IDs in your language of choice and do a SELECT ... WHERE id IN(x)
Query select count(*) from users; returns 10293453. Query SELECT id FROM users ORDER BY RAND() LIMIT 10; runs 5 sec.
Just found your solution. Thank you for it. It's incredible easy and exactly what I was looking for. Thanks!
your solution works, but it gets slow when you have over millions of rows at your table. So, I suggest to generate a random number in php and send it to sql query.
5
select * from table order by rand() limit 10

Note that order by rand() with large dataset is very slow but in your case it's not a problem.

Comments

3

you could do that using RAND() function .

SELECT questine FROM tablename ORDER BY RAND() LIMIT 10

will select 10 questines at random under assumption the questine is stored under field questine

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.