Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting random rows with MySQL

Tags:

random

mysql

I saw many topics about this subject and I have been unsuccessful in understanding how to do it.

For example, if I have this table:

+------+-------+-------+
| id   | name  | class |
+------+-------+-------+
|    5 | test  | one   | 
|   10 | test2 | one   | 
|   12 | test5 | one   | 
|    7 | test6 | two   | 
+------+-------+-------+

and I want to show only X random rows from class "one", how can I do that?

NOTE: it's a big table, so I don't want to use ORDER BY RAND.

like image 476
Daniel Avatar asked Jun 30 '11 22:06

Daniel


People also ask

How do I select multiple rows in MySQL?

To select last two rows, use ORDER BY DESC LIMIT 2.

How do I select a random row by group in SQL?

Below SQL statement is to display the defined number of random rows from a table using RAND() function: Query: SELECT * FROM table_name order by RANDOM() LIMIT n; In table_name mention your Table Name and in the place of 'n' give how many rows to be fetched.

How do I shuffle data in MySQL?

If you need the rows in a random order, grab the required number of rows and then use PHP's shuffle function on the array of rows returned. There can be quite a performance penalty with using ORDER BY RAND() in a query, depending on how many records there are.


1 Answers

The ORDER BY RAND() solution that most people recommend doesn't scale to large tables, as you already know.

SET @r := (SELECT FLOOR(RAND() * (SELECT COUNT(*) FROM mytable)));
SET @sql := CONCAT('SELECT * FROM mytable LIMIT 1 OFFSET ', @r);
PREPARE stmt1 FROM @sql;
EXECUTE stmt1;

I cover this and other solutions in my book, SQL Antipatterns: Avoiding the Pitfalls of Database Programming.


If you want to do this with PHP, you could do something like this (not tested):

<?php
$mysqli->begin_transaction();
$result = $mysqli->query("SELECT COUNT(*) FROM mytable")
$row = $result->fetch_row(); 
$count = $row[0]; 
$offset = mt_rand(0, $count);
$result = $mysqli->query("SELECT * FROM mytable LIMIT 1 OFFSET $offset");
...
$mysqli->commit();
like image 199
Bill Karwin Avatar answered Oct 27 '22 10:10

Bill Karwin