Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting Random Rows in MySQL

Tags:

sql

mysql

I am developing a quiz website, and I have a database which stores all of the questions. There are different types of quizzes, like math, science, history, etc. All of the questions are stored in one table.

My questions table looks like this:

questions ( qno(int)  ,type(int), question, .... ,... )

qno is the primary key, and type is used to keep track of the quiz type.:

if type = 1 (math)
 type = 2(science)

Now, I want to select some random questions for each type of test. For example, I may want to select some random 20 questions for only the math test.

Does MySQL have some way to select random rows?

like image 608
user156073 Avatar asked Aug 16 '09 07:08

user156073


2 Answers

You can use the rand function in MySQL to order the rows, and then take the top 10 (or however many you want) with limit.

select * from table order by rand() limit 10

If you want just the math questions:

select * from table where type = 1 order by rand() limit 10
like image 129
Eric Avatar answered Sep 23 '22 19:09

Eric


Add a column to your table that will hold a UNIX timestamp.

Once a day or any timeframe which works for you, you run a query that updates that column.

In this case your query should run at midnight and look something like this.

UPDATE table SET rand_id = (UNIX_TIMESTAMP() + (RAND() * 86400));

Then to retrieve the rows, you use a query similar to this.

SELECT * FROM table WHERE rand_id > UNIX_TIMESTAMP() ORDER BY rand_id ASC LIMIT 20

Using a column with a pre-determined random value saves you needing to run a randomization function for every single row in the table for every single request to the page.

like image 26
joebert Avatar answered Sep 24 '22 19:09

joebert