473,750 Members | 2,182 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Random sample from MySQL Database

Hi all,

I am trying to fetch 5 records, randomly picked and in random order
from a MySQL table (MySQL version > 3.23).

I wrote my SQL Query as

SELECT name,id FROM tablename WHERE active = 'Y' ORDER BY RAND() LIMIT
5

But its not working. It returns records in a fixed order every time.
Can anybody suggest why its not working the expected way?

I found an alternative solution and used the following query

SELECT name,id FROM tablename WHERE active = 'Y' ORDER BY MD5(RAND())
LIMIT 5

Its working fine :-)

But still i am not clear why the first query is failing? :-(

Thanks in advance.

-- Rahul
Jul 17 '05 #1
4 13586

On 25-Dec-2003, ra************@ rediffmail.com (Rahul Anand) wrote:
I am trying to fetch 5 records, randomly picked and in random order
from a MySQL table (MySQL version > 3.23).

I wrote my SQL Query as

SELECT name,id FROM tablename WHERE active = 'Y' ORDER BY RAND() LIMIT
5

But its not working. It returns records in a fixed order every time.
Can anybody suggest why its not working the expected way?

I found an alternative solution and used the following query

SELECT name,id FROM tablename WHERE active = 'Y' ORDER BY MD5(RAND())
LIMIT 5

Its working fine :-)

But still i am not clear why the first query is failing? :-(

Thanks in advance.


I was unable to reproduce your problem. My query returned 5 random records
in random sequence each time..

--
Tom Thackrey
www.creative-light.com
tom (at) creative (dash) light (dot) com
do NOT send email to ja*********@wil lglen.net (it's reserved for spammers)
Jul 17 '05 #2
Rahul Anand wrote:

Hi all,

I am trying to fetch 5 records, randomly picked and in random order
from a MySQL table (MySQL version > 3.23).

I wrote my SQL Query as

SELECT name,id FROM tablename WHERE active = 'Y' ORDER BY RAND() LIMIT
5

But its not working. It returns records in a fixed order every time.
Can anybody suggest why its not working the expected way?


From http://www.mysql.com/doc/en/Mathemat...unctions.html:

You can't use a column with RAND() values in an ORDER BY clause, because ORDER
BY would evaluate the column multiple times. From version 3.23 you can do:
SELECT * FROM table_name ORDER BY RAND() This is useful to get a random sample
of a set SELECT * FROM table1,table2 WHERE a=b AND c<d ORDER BY RAND() LIMIT
1000. Note that a RAND() in a WHERE clause will be re-evaluated every time the
WHERE is executed. RAND() is not meant to be a perfect random generator, but
instead a fast way to generate ad hoc random numbers that will be portable
between platforms for the same MySQL version.
So try:

SELECT * FROM tablename WHERE active = 'Y' ORDER BY RAND() LIMIT 5

and my guess is you'll get your result.

Regards,
Shawn
--
Shawn Wilson
sh***@glassgian t.com
http://www.glassgiant.com
Jul 17 '05 #3
Shawn Wilson <sh***@glassgia nt.com> wrote in message news:<3F******* ********@glassg iant.com>...
Rahul Anand wrote:

Hi all,

I am trying to fetch 5 records, randomly picked and in random order
from a MySQL table (MySQL version > 3.23).

I wrote my SQL Query as

SELECT name,id FROM tablename WHERE active = 'Y' ORDER BY RAND() LIMIT
5

But its not working. It returns records in a fixed order every time.
Can anybody suggest why its not working the expected way?


From http://www.mysql.com/doc/en/Mathemat...unctions.html:

You can't use a column with RAND() values in an ORDER BY clause, because ORDER
BY would evaluate the column multiple times. From version 3.23 you can do:
SELECT * FROM table_name ORDER BY RAND() This is useful to get a random sample
of a set SELECT * FROM table1,table2 WHERE a=b AND c<d ORDER BY RAND() LIMIT
1000. Note that a RAND() in a WHERE clause will be re-evaluated every time the
WHERE is executed. RAND() is not meant to be a perfect random generator, but
instead a fast way to generate ad hoc random numbers that will be portable
between platforms for the same MySQL version.
So try:

SELECT * FROM tablename WHERE active = 'Y' ORDER BY RAND() LIMIT 5

and my guess is you'll get your result.

Regards,
Shawn

Hi Shawn,

I also have read the documentation about this:-

"You can't use a column with RAND() values in an ORDER BY clause,
because ORDER
BY would evaluate the column multiple times."

As i interpret:
It says you cant use a RAND() column in *select-field-list* as well as
in ORDER BY clause because with each call RAND() will return a
different number.

You can not use it in where clause either for the same reason.

My query does not use RAND() in select-field-list or where clause.

I checked my first query in MySQL ver 4.1 and its working fine.

As per documentation:

"From version 3.23 you can do:
SELECT * FROM table_name ORDER BY RAND()"

But i am unable to do this in my MySQL 3.23.54

--
regards,
Rahul
Jul 17 '05 #4

On 26-Dec-2003, ra************@ rediffmail.com (Rahul Anand) wrote:
"From version 3.23 you can do:
SELECT * FROM table_name ORDER BY RAND()"

But i am unable to do this in my MySQL 3.23.54


It works for me on 3.23.55, I think you have some other problem.

--
Tom Thackrey
www.creative-light.com
tom (at) creative (dash) light (dot) com
do NOT send email to ja*********@wil lglen.net (it's reserved for spammers)
Jul 17 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
2961
by: Bart Nessux | last post by:
New to Python... trying to figure out how to count the objects in a list and then map the count to the objects or convert the list to a dict... I think the latter would be better as I need a number associated with each entry. Any pointers? Also, does this bit of code look to be truely random? def random_number_gen(): winner = winner.append(random.sample(xrange(100000), 1))
9
2256
by: Bart Nessux | last post by:
I am using method 'a' below to pick 25 names from a pool of 225. A co-worker is using method 'b' by running it 25 times and throwing out the winning name (names are associated with numbers) after each run and then re-counting the list and doing it all over again. My boss thinks that 'b' is somehow less fair than 'a', but the only thing I see wrong with it is that it is really inefficient and ugly as it's doing manually what 'a' does...
0
573
by: Jason McCormick | last post by:
Hello all, I was wondering if someone could shed some light on this problem I'm having. I have 3 slave MySQL servers replication from a master machine. The master machine is running only MySQL while the slave machines are an Apache + Tomcat + MySQL web service. All slave machines are precisely identical. I'm running into a situation where (seemly at random) after a month or two of consistently flawless performance, just ONE of the...
0
1471
by: Tony Stephens | last post by:
I have a database table that contains a set of numbers (set X). I need to be able to generate/export a random set of survey numbers (set C) from set A with IDs that aren't in set B. Where set A is a subset of numbers from set X that match the filters for the survey, and set B contains the set of number IDs for numbers that have already been exported for the survey. The idea is to repeatedly generate a random sample of non-duplicate...
1
4720
by: steflhermitte | last post by:
Dear cpp-ians, I want to apply a stratified sampling on an image. Following simplified example will explain my problem. The original image I with nrows and ncols is now a vector V of length (nrow x ncol) and every element of the vector contians its pixel value. vector float V ;
1
1752
by: jaYPee | last post by:
I am planning to use mysql and vb.net to my new project. this is an enrollment system. I want to know where can i find sample of vb.net that connects to mysql database. thanks in advance
3
2359
by: VB.NET | last post by:
I'm using a mysql database and connecting my vb.net program to the DB over a network connection. i would like to bring this data over to a vb.net random access file. does anyone know how to convert my DB into a binary file? and how to convert my code to use a file instead of the db?
12
5228
by: Jim Michaels | last post by:
I need to generate 2 random numbers in rapid sequence from either PHP or mysql. I have not been able to do either. I get the same number back several times from PHP's mt_rand() and from mysql's RAND(). any ideas? I suppose I could use the current rancom number as the seed for the next random number. but would that really work?
26
3153
by: Jimmy | last post by:
ill have a database with 1 table and 3 fields: ID FIRSTNAME LASTNAME (the ID field will be the auto incrementing index) there might be 10 records in the DB, there might be 10,000. i need to open the DB and randomly select a record (and then display the name, which i dont have a problem with) how can i randomly select a record? im guessing id have to open a recordset
0
8999
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9575
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9256
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6803
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6080
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4712
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4885
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3322
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2223
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.