Search code examples
mysqlsqllimit

How to ORDER BY RAND() and set LIMIT randomly?


I want to extract random rows and I want the number of rows to variate every time I run
How can I make that happen?

This is my table

CREATE TABLE sbb_data (
    scope_node VARCHAR(25), 
    site VARCHAR(20), 
    name VARCHAR(40),  
    is_deleted INT, 
    is_connected INT
);

SELECT name FROM sbb_data;

Output

SBB 1
SBB 2
SBB 3
SBB 4
SBB 5
SBB 6
SBB 7
SBB 8
SBB 9
SBB 10
SBB 11

When I run the following query

SELECT name FROM sbb_data ORDER BY RAND() LIMIT 0,5;

I get something like this

SBB 8
SBB 9
SBB 2
SBB 10
SBB 4

But the number of rows output is always 5

I want it to variate between 0,5


Solution

  • Pick 5 rows at random, then assign them a new random number; pick rows where the new random number is less than 0.5 (picking, on average, half the numbers, but possibly none, possibly all over them).

    SELECT *
      FROM (SELECT * FROM sbb_data ORDER BY RAND() LIMIT 0,5) rand5
     WHERE RAND() < 0.5
    

    For example: https://dbfiddle.uk/?rdbms=mysql_5.7&fiddle=c80a90b08e77e5e6448991d589f39df4