RAND() function in MySql

July 20, 2003 by  
Filed under Code Snippets

I was trying to use this query to get a random row from the database:

$myRandom = "SELECT * FROM MYTABLE ORDER BY RAND() LIMIT 1";

and I couldn’t figure out why it would continually get the previous number instead of some random number.

Ahh, but look what’s at the bottom of the page. ;)

“As of MySQL 3.23.52, MySQL changed the way RAND() functions, such that you MUST supply a SEED to get an actual random number. If you do not, each new connection will return close to the same number as the previous new connection. An example to test this would be to run the follow command multiple times in a row. mysql -u username -p -e’select rand()’ A basic way to seed this would be to run RAND(NOW()).”

So now I know, I must provide a random seed. ;)

Source: http://www.mysql.com

Related Products:

Energizer AA Batteries, Double A Battery Max Alkaline (24 Count) E91BP-24Energizer AA Batteries, Double A Battery Max Alkaline (24 Count) E91BP-24Long-lasting power and innovation is what Energizer MAX is all about. Introducing our longest-lasting Energizer MAX battery yet. With our latest impro... Read More >
All-New Fire HD 10 Tablet with Alexa Hands-Free, 10.1" 1080p Full HD Display, 32 GB, Black - with Special OffersAll-New Fire HD 10 Tablet with Alexa Hands-Free, 10.1" 1080p Full HD Display, 32 GB, Black - with Special Offers

The all-new Fire HD 10 features our largest display, now in 1080p Full HD, 32 GB storage, 2 GB RAM, and up to 10 hours of battery. Now with Alexa... Read More >

Related Posts Plugin for WordPress, Blogger...