473,847 Members | 1,453 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Problem with ORDER BY and random() ?

Hello,

I'm trying to retrieve a limited number of random rows, and order them by a
column, and am not having any luck with that last part:

SELECT * FROM tablename ORDER BY random(), id LIMIT 10

Returns everything more or less as expected, except for the fact that the
results aren't sorted by "id" ...

I also tried:

SELECT random() as sorter, * FROM tablename ORDER BY sorter, id LIMIT 10

But that didn't change anything either.

I tried sorting on a column other than "id", but that didn't work any better
:(

I also tried this on 7.2.1 and 7.3.1 (Both on RH 7.3), thinking this
might've been a bug.

A quick read of the docs suggests sorting on multiple columns is perfectly
legal, as it is used as an example.

atlas=# select id from quiz_questions_ english order by random(), id limit
10;
id
-----
445
756
393
809
335
682
776
754
379
739
(10 rows)

atlas=# select random() as sorter, id from quiz_questions_ english order by
sorter, id limit 10;
sorter | id
----------------------+-----
0.0007573887709 32978 | 455
0.0080651594363 4564 | 440
0.0083680739665 2553 | 386
0.0097777526871 1976 | 323
0.0104504898239 162 | 370
0.0166072882789 221 | 778
0.0202831137088 514 | 416
0.0306016304672 703 | 762
0.0340994806187 691 | 772
0.0384632679812 905 | 371
(10 rows)

Anybody know what's going on here ? I've tried this from Zope/psycopg,
pgAdminII, and psql ... removing the limit doesn't do any good, and neither
does using ASC or DESC !

Any help would be greatly appreciated !!

Thanks in advance,

Jean-François Doyon
Internet Service Development and Systems Support
GeoAccess Division
Canadian Center for Remote Sensing
Natural Resources Canada
http://atlas.gc.ca
Phone: (613) 992-4902
Fax: (613) 947-2410
---------------------------(end of broadcast)---------------------------
TIP 4: Don't 'kill -9' the postmaster

Nov 11 '05 #1
7 10668
Centuries ago, Nostradamus foresaw when Je************* ****@CCRS.NRCan .gc.ca would write:
I'm trying to retrieve a limited number of random rows, and order them by a
column, and am not having any luck with that last part:

SELECT * FROM tablename ORDER BY random(), id LIMIT 10

Returns everything more or less as expected, except for the fact that the
results aren't sorted by "id" ...


I'm not sure why you are surprised at this. You asked to order them
primarily by random(), and then by id, if the random values were
equal, and that is clearly the order that you are getting.

If you want to order the 10 records by id, you might accomplish that
by the following:

select * from (select * from tablename order by random() limit 10)
order by id;
--
let name="cbbrowne" and tld="cbbrowne.c om" in name ^ "@" ^ tld;;
http://www3.sympatico.ca/cbbrowne/finances.html
Rules of the Evil Overlord #62. "I will design fortress hallways with
no alcoves or protruding structural supports which intruders could use
for cover in a firefight." <http://www.eviloverlor d.com/>
Nov 11 '05 #2
I just searched all the 7.2 manuals, the latest I have, and there is not
one explanation of using random to order a query........

Je************* ****@ccrs.nrcan .gc.ca wrote:
Hello,

I'm trying to retrieve a limited number of random rows, and order them by a
column, and am not having any luck with that last part:

SELECT * FROM tablename ORDER BY random(), id LIMIT 10

Returns everything more or less as expected, except for the fact that the
results aren't sorted by "id" ...

I also tried:

SELECT random() as sorter, * FROM tablename ORDER BY sorter, id LIMIT 10

But that didn't change anything either.

I tried sorting on a column other than "id", but that didn't work any better
:(

I also tried this on 7.2.1 and 7.3.1 (Both on RH 7.3), thinking this
might've been a bug.

A quick read of the docs suggests sorting on multiple columns is perfectly
legal, as it is used as an example.

atlas=# select id from quiz_questions_ english order by random(), id limit
10;
id
-----
445
756
393
809
335
682
776
754
379
739
(10 rows)

atlas=# select random() as sorter, id from quiz_questions_ english order by
sorter, id limit 10;
sorter | id
----------------------+-----
0.0007573887709 32978 | 455
0.0080651594363 4564 | 440
0.0083680739665 2553 | 386
0.0097777526871 1976 | 323
0.0104504898239 162 | 370
0.0166072882789 221 | 778
0.0202831137088 514 | 416
0.0306016304672 703 | 762
0.0340994806187 691 | 772
0.0384632679812 905 | 371
(10 rows)

Anybody know what's going on here ? I've tried this from Zope/psycopg,
pgAdminII, and psql ... removing the limit doesn't do any good, and neither
does using ASC or DESC !

Any help would be greatly appreciated !!

Thanks in advance,

Jean-Fran?ois Doyon
Internet Service Development and Systems Support
GeoAccess Division
Canadian Center for Remote Sensing
Natural Resources Canada
http://atlas.gc.ca
Phone: (613) 992-4902
Fax: (613) 947-2410
---------------------------(end of broadcast)---------------------------
TIP 4: Don't 'kill -9' the postmaster

---------------------------(end of broadcast)---------------------------
TIP 6: Have you searched our list archives?

http://archives.postgresql.org

Nov 11 '05 #3
On Tue, 23 Sep 2003 Je************* ****@ccrs.nrcan .gc.ca wrote:
Hello,

I'm trying to retrieve a limited number of random rows, and order them by a
column, and am not having any luck with that last part:

SELECT * FROM tablename ORDER BY random(), id LIMIT 10

Returns everything more or less as expected, except for the fact that the
results aren't sorted by "id" ...


Of course not, they're already sorted randomly. i.e. random() assigns a
value between 0 and 1 like so:

select random(),aid from accounts limit 10;
random | aid
--------------------+-----
0.4169376154509 08 | 1
0.3982051952733 68 | 2
0.4012232527142 5 | 3
0.6857562822689 1 | 4
0.0215648445401 177 | 5
0.0346587472756 667 | 6
0.9061036034981 27 | 7
0.3471873385585 79 | 8
0.8332442309862 21 | 9
0.7864848979685 85 | 10

So, if we make a subselect, we get:

select * from (select random() as r,aid from accounts limit 10) as a
order by a.r;
r | aid
--------------------+-----
0.0806112047660 217 | 8
0.0979125742325 152 | 4
0.2064584601700 58 | 9
0.4928860801704 63 | 5
0.5359665865711 71 | 6
0.5537159045011 35 | 2
0.6319265671223 06 | 7
0.7619180063539 73 | 10
0.9021837855233 74 | 3
0.9781994293342 34 | 1

We can see what number we were ordering by. Since the chances of having
two random numbers be the same float is pretty close to zero, the order by
random(),id will never get to the id, because random() has no repeating
values.
---------------------------(end of broadcast)---------------------------
TIP 2: you can get off all lists at once with the unregister command
(send "unregister YourEmailAddres sHere" to ma*******@postg resql.org)

Nov 11 '05 #4
Je************* ****@CCRS.NRCan .gc.ca writes:
I'm trying to retrieve a limited number of random rows, and order them by a
column, and am not having any luck with that last part:
SELECT * FROM tablename ORDER BY random(), id LIMIT 10
Returns everything more or less as expected, except for the fact that the
results aren't sorted by "id" ...


Well, no. You specified random() as the major sort key. Only rows that
happened to have equal random() values would be sorted by id.

This would work:

SELECT * FROM
(SELECT * FROM tablename ORDER BY random() LIMIT 10) as ss
ORDER BY id;

regards, tom lane

---------------------------(end of broadcast)---------------------------
TIP 4: Don't 'kill -9' the postmaster

Nov 11 '05 #5

On Tue, 23 Sep 2003 Je************* ****@CCRS.NRCan .gc.ca wrote:
Hello,

I'm trying to retrieve a limited number of random rows, and order them by a
column, and am not having any luck with that last part:

SELECT * FROM tablename ORDER BY random(), id LIMIT 10

Returns everything more or less as expected, except for the fact that the
results aren't sorted by "id" ...


The above basically says sort by random() and then for equal values of
that sort those by id. That's not going to sort by id really except in
cases that random() gave the same value. You probably wanted something
with a subselect that did the limiting with the order by on the outside,
like:
SELECT * from (SELECT * FROM tablename ORDER BY random() LIMIT 10) as foo
ORDER BY id;

However, this is a fairly expensive way to generate random rows for a big
table. The archives should have some better mechanisms in them.

---------------------------(end of broadcast)---------------------------
TIP 6: Have you searched our list archives?

http://archives.postgresql.org

Nov 11 '05 #6
Je************* ****@CCRS.NRCan .gc.ca wrote:
Hello,

I'm trying to retrieve a limited number of random rows, and order them by a
column, and am not having any luck with that last part:

SELECT * FROM tablename ORDER BY random(), id LIMIT 10


How about:

SELECT * FROM
(SELECT * FROM tablename ORDER BY random() LIMIT 10) AS data
ORDER BY id;

HTH,

Mike Mascari
ma*****@mascari .com

---------------------------(end of broadcast)---------------------------
TIP 2: you can get off all lists at once with the unregister command
(send "unregister YourEmailAddres sHere" to ma*******@postg resql.org)

Nov 11 '05 #7
On Tue, 23 Sep 2003 Je************* ****@CCRS.NRCan .gc.ca wrote:
Hello,

I'm trying to retrieve a limited number of random rows, and order them by a
column, and am not having any luck with that last part:

SELECT * FROM tablename ORDER BY random(), id LIMIT 10
So it's sorting by random() then id.
Returns everything more or less as expected, except for the fact that the
results aren't sorted by "id" ...
Well it's sorting by random() then id.
SELECT random() as sorter, * FROM tablename ORDER BY sorter, id LIMIT 10
Sorting by sorter then id.
But that didn't change anything either.
Well it wouldn't because it's sorting by random() then id. :)
I tried sorting on a column other than "id", but that didn't work any better
:(
Well no. It's sorting by random() then some column other than id. :))
I also tried this on 7.2.1 and 7.3.1 (Both on RH 7.3), thinking this
might've been a bug.
Looks alright to me.
A quick read of the docs suggests sorting on multiple columns is perfectly
legal, as it is used as an example.
Yep, but then the example probably isn't trying to sort by random() then
id. :)))
atlas=# select id from quiz_questions_ english order by random(), id limit
10;
id
-----
445
756
393
809
335
682
776
754
379
739
(10 rows)
So it's sorting by random() the id? *big big grin*
atlas=# select random() as sorter, id from quiz_questions_ english order by
sorter, id limit 10;
sorter | id
----------------------+-----
0.0007573887709 32978 | 455
0.0080651594363 4564 | 440
0.0083680739665 2553 | 386
0.0097777526871 1976 | 323
0.0104504898239 162 | 370
0.0166072882789 221 | 778
0.0202831137088 514 | 416
0.0306016304672 703 | 762
0.0340994806187 691 | 772
0.0384632679812 905 | 371
(10 rows)
Ah, yes, I see now, it's sorting by random() then id. *falls on floor giggling
like a little school girl*
Anybody know what's going on here ? I've tried this from Zope/psycopg,
pgAdminII, and psql ... removing the limit doesn't do any good, and neither
does using ASC or DESC !


Sheesh, now all I've got to do is remember the suggested ways of doing this.

select *
from (select random(), id from quiz_questions order by 1 limit 10) ss
order by id
should at least get you closer I think.
--
Nigel J. Andrews
---------------------------(end of broadcast)---------------------------
TIP 5: Have you checked our extensive FAQ?

http://www.postgresql.org/docs/faqs/FAQ.html

Nov 11 '05 #8

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

Similar topics

4
6114
by: noone | last post by:
hello all. I am using this code to randomly select one value from an array. srand (); $rec = array("1","2","3","4","5","6"); $rec = $rec; print $rec; problem is, is sometimes it returns nothing. can anyone see how to make this so it always selects something.
5
2907
by: Ross MacGregor | last post by:
I have a very simple yet complicated problem. I want to generate a random list of indices (int's) for a container. Let's say I have a container with 10 items and I want a list of 3 random indices for that container. So I need to generate 3 unique numbers from integer range . There seems to be no simple and efficient way to do this. Any implementation I have come up with involves maintaining a list of
4
2506
by: lharby | last post by:
I'm hoping this is very simple. I am currently using a random quote generator on our intranet. I have 17 quotes, when I add in an 18th and change the makeArray number the code seems not to work. This works: <script LANGUAGE="JavaScript"> function makeArray(len) {
6
1780
by: Sen-Lung Chen | last post by:
Dear All: I have a question about this below function.The purpose of this function is to generate one number between a and b. -------------------------- int gennum(int a, int b) { srand(time(NULL)); int range = b-a+1; int x = (rand())%range;<-- problem occur here int result = a+x;
5
11365
by: Greg Brady | last post by:
Is there a way to return a random sort order from a query?
10
1665
by: Curt_C [MVP] | last post by:
If I use it in my page it's fine but when I put it in a Class file for calling it returns the same # for each call. Any ideas why? I'm sure it's something I'll slap myself for but the only samples I can find are for calling the Random() within the page, not a seperate class. --Page-- myClass myclass = new myClass(); for(int i = 1;i <= 100; i++) {
5
1316
Savage
by: Savage | last post by:
Of 7 random numbers it's happening that some of these numbers are the same. I tryed to use do-while loop to fix this, but problem still consist. Here is the code: input: enum bool {FALSE,TRUE}; unsigned int a,b,p,q; int x,y,k,i,j,L,kk,xi,yi; int e,w;
0
9889
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
9732
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10988
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...
1
10712
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10344
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...
0
9487
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5723
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...
1
4536
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
3166
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.