Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8376537
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T15:27:11+00:00 2026-06-09T15:27:11+00:00

I have a query which aims to retrieve a random row from a result

  • 0

I have a query which aims to retrieve a random row from a result set. I do not want to use ORDER BY Rand() as it seems to be rather inefficient.

My method is as follows:

  • generate a single random number between [0,1)
  • give each row of the result query a unique ‘rank’ number. i.e. give the first row a value 1, second row a value 2, and so forth
  • use the random number to get a number between 1 and the number of rows in the result
  • return the row where rank == the number generated from the random number

example query:

SELECT * FROM(

    (SELECT @rand := RAND(), @rank := 0) r1
    CROSS JOIN
    (SELECT (@rank:=@rank+1) as num, A.id FROM
    A JOIN B
    ON A.id = B.id
    WHERE B.number = 42
)
WHERE num = FLOOR(1 + @rand * @rank) LIMIT 1

This works for retrieving one row, but I instead want 10 random rows. Changing LIMIT 1 to LIMIT 10 doesn’t work, because if num + 10 > number of rows the query doesn’t return 10 rows.

The only solution I can think of it to either generate 10 random numbers in the sql query, check they are all different from each other and have several WHERE num = random_number_1 lines. Alternatively, I could call the query 10 times, checking that the rows selected are unique. I wouldn’t know how to do the former, and the latter seems like it is rather inefficient. Unless there is likely to be some wonderful cache that would make running the same query extremely fast?

Does anyone have any ideas? thank you

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-09T15:27:12+00:00Added an answer on June 9, 2026 at 3:27 pm

    You could try the following:

    select sq2.c1 
      from  ( select * 
                from (select @count :=  0) sq0
               cross join  
                     (select t1.c1, @count := @count+1        
                        from t t1       
                        join t t2      
                       using(c1)      
                       where t2.c2 = 42    
                     ) sq1  
             ) sq2   
     --use a probability to pick random rows
     where if(@count <= 5, 1, floor(1 + rand() * (@count-1))) <= ceiling(log(pow(@count,2)))+1
     limit 5;
    

    The results will be random unless the result set is smaller (or the same size as) the limit. If this is a problem, you can wrap the whole thing:

    select sq3.* from ( select ... limit 5 ) sq3 
    order by rand().  
    

    This will only randomize the small number of output rows (at most 5) which is efficient.

    Of course, you can always use a temporary table:

    create temporary table rset (row_key int auto_increment, key(row_key))
    as ( select .... where c2 = 42 ) engine=myisam;
    
    set @count := select count(*) from rset;
    
    select rset.c1 
      from rset 
     where row_key in (    (floor(1 + rand() * (@count-1))),
    (floor(1 + rand() * (@count-1))),
    (floor(1 + rand() * (@count-1))),
    (floor(1 + rand() * (@count-1))),
    (floor(1 + rand() * (@count-1))) );
    
    drop table rset;
    

    If you want to guarantee that you get five unique rows, then you can use a second temporary table:

    create temporary table row_keys ( row_key int not null primary key );
    -- do this successful five times.  if you get a unique key error try again
    insert into row_keys values (floor(1 + rand() * (@count-1));
    
    select rset.c1
      from rset
      join row_keys
      using(row_key);
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Possible Duplicate: Retrieve column names from java.sql.ResultSet I have query which returns the result
I have a query which returns a result set which looks like this: A
i have a query which i want to simplify: select sequence, 1 added from
I have a query which returns the result set as follows: Col1 A B
I have SQL query which goes to result table: $php_variable_answer = SELECT answer_id FROM
I have a query which has an Order By clause. The generated SQL from
I have a query which returns two rows of data as count. I want
I have this query which groups the results by ORDER#. SELECT ORDER#, MAX(SHIPDATE -
I have a query which looks like this: SELECT LossCost, CoverageID FROM BGILossCost] WHERE
I have a query which returns a series of cells of data from a

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.