Select random data (mysql)

Post at Mon, 05.October.2009 12:58:26 PM .
Hit: 496 . Comment: 3
 
 
Sometimes, we need random data for showing in our home page, example : random product, random photo, etc. To get random data, we can just put a simple script to our mysql query.
Just use "rand()" funtion.  Here the example :

First, we create new database and table for this sample.

create database `db_test`;

use `db_test`;

CREATE TABLE `member` (                 
          `id` int(11) NOT NULL auto_increment, 
          `name` varchar(100) default NULL,     
          `location` varchar(100) default NULL, 
          PRIMARY KEY  (`id`)                   
        );

insert  into `member`(`id`,`name`,`location`) values (1,'Jerry','New York'),(2,'Anastasya','Sydney'),(3,'Rudy','Hawai'),(4,'Sonoko','Tokyo'),(5,'Fredy','Singapore'),(6,'Anne ','Beijing'),(7,'Hannah','Silicon Valley'),(8,'Derick','Singapore'),(9,'Johan','Jakarta'),(10,'Teo','Seoul');
















For example, we need 5 random member for show in our home page, so we can use this query
select * from member
order by rand()
limit 5;





We use 'limit 5' because we want limit the result just 5 random data. Every time you execute this query, the result will be different.
 

 

Comments for "Select random data (mysql)"

08.October.2009 05:08:24 PM
order by rand() is not recommended even you limit 1; because it will random all your data first. to avoid it better use where id in(rand_no1,rand_no2)
08.October.2009 07:05:03 PM
anton..thx for the advice. Yup, you're right , it's not recommended if the data in our database is big, but if the data in our database not very big, why not we use it :D ( It will shorten our code => just for lazy programmer like me :P ).
sh
13.December.2009 02:01:56 AM
ow thx for this great tutorial too :p
Name*
E-mail* (not published)
URL
Comment*
Enter validation code

 
 
Sat, 04.September.2010
Today Visitor : 31
You are visitor No. 419619

Advertisement