Posted By

BFTrick on 04/20/09


Tagged

random


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

rickfu


Get random record in table


 / Published in: MySQL
 

This code is useful if you have a table where some records have been deleted. This code will favor records after large blocks of deleted records.

1) Get max id 2) generate random number with the max id 3) Query DB with random number.

  1. SELECT MAX(id) FROM table
  2.  
  3. <?php
  4. $random_num = RAND(0, $max(id));
  5. ?>
  6.  
  7. SELECT * FROM table WHERE id >= $random_num LIMIT 1

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: CoryMathews on April 20, 2009

This is not mysql... this is php.

Posted By: april198474 on September 23, 2009

You can try this to select a random row with Microsoft SQL Server:

SELECT TOP 1 column FROM table ORDER BY NEWID()


April

http://www.comm100.com/livechat/

You need to login to post a comment.