pg.ddx.io  pgsql-sql@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Tom Lane <tgl@sss.pgh.pa.us>
To: dgreer@websightsolutions.com
Cc: pgsql-sql@postgreSQL.org
Subject: Re: [SQL] More fun with random selects
Date: Wed, 30 Jun 1999 10:28:51 -0400
Message-ID: <22060.930752931@sss.pgh.pa.us> (raw)
In-Reply-To: <9906300730281H.06064@george>

Darren Greer <dgreer@websightsolutions.com> writes:
> For example, lets say I want a random 125 rows from an existing table.  Is
> there an easy way I can do that where I actually am getting a decent sample
> from the table?

I don't think there's any way to do that with a simple SQL command.

It's possible to draw exactly N items from a set fully randomly if you
are willing to write a little code.  The algorithm looks like this:

	itemsRemaining = size of set (# rows in table);
	itemsStillNeeded = N (# rows wanted, 125 in your example);
	foreach (item in set)
	{
		generate random value X that is 'true' with probability
			itemsStillNeeded / itemsRemaining;
		if (X)
		{
			emit current item as a selected item;
			decrement itemsStillNeeded;
			if (itemsStillNeeded == 0) done;
		}
		decrement itemsRemaining;
	}

The random choice is typically done with a random number generator
that generates output G between say 0 and M; you make X 'true' if
G <= M * itemsStillNeeded / itemsRemaining.

			regards, tom lane



view thread (2+ messages)

Message-ID: <22060.930752931@sss.pgh.pa.us>
Permalink:  ../22060.930752931@sss.pgh.pa.us/
Also on:    postgresql.org/message-id/22060.930752931@sss.pgh.pa.us

 · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients from your mail client; the link fills in
  the headers below: reply via email
  Some clients, webmail especially, drop In-Reply-To and References from
  a link, and the reply then starts a new thread: use the mbox below.

  To: pgsql-sql@postgresql.org
  Cc: tgl@sss.pgh.pa.us, dgreer@websightsolutions.com
  Subject: Re: [SQL] More fun with random selects
  In-Reply-To: <22060.930752931@sss.pgh.pa.us>
  References: <9906300730281H.06064@george> <22060.930752931@sss.pgh.pa.us>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox