pg.ddx.io  pgsql-general@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Condor <condor@stz-bg.com>
To: Ryan Murphy <ryanfmurphy@gmail.com>
Cc: PostgreSQL mailing lists <pgsql-hackers@postgresql.org>
Cc: pgsql-general@postgresql.org
Subject: Re: Best way to select a random row from a derived table
Date: Sun, 28 Jan 2018 12:09:35 +0200
Message-ID: <9289a7a28f356e9b27ae2e93f4551a86@stz-bg.com> (raw)
In-Reply-To: <CAHeEsBfP2DL2B+VwDZSoxMjz7KPTD2oFg0RDE-SRJ+gRn4wzXA@mail.gmail.com>
References: <CAHeEsBfP2DL2B+VwDZSoxMjz7KPTD2oFg0RDE-SRJ+gRn4wzXA@mail.gmail.com>

On 28-01-2018 08:39, Ryan Murphy wrote:
> Hello hackers and postgressers,
> 
> I am aware of 2 ways to select a random row from a table:
> 
>     1) select * from table_name order by random() limit 1;
>         -- terribly inefficient
> 
>     2) select * from table_name tablesample system_rows(1) limit 1;
>         -- only works on tables, not views or subqueries
> 
> Is there an option that is reasonably efficient and can be used on
> views and subqueries?
> 
> Thanks!
> Ryan


I do it with:

SELECT * FROM table_name OFFSET RANDOM() * LIMIT 1;

Regards,
HC




view thread (3+ messages)

Message-ID: <9289a7a28f356e9b27ae2e93f4551a86@stz-bg.com>
Permalink:  ../9289a7a28f356e9b27ae2e93f4551a86@stz-bg.com/
Also on:    postgresql.org/message-id/9289a7a28f356e9b27ae2e93f4551a86@stz-bg.com

 · 

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-general@postgresql.org
  Cc: condor@stz-bg.com, ryanfmurphy@gmail.com, pgsql-hackers@postgresql.org
  Subject: Re: Best way to select a random row from a derived table
  In-Reply-To: <9289a7a28f356e9b27ae2e93f4551a86@stz-bg.com>
  References: <CAHeEsBfP2DL2B+VwDZSoxMjz7KPTD2oFg0RDE-SRJ+gRn4wzXA@mail.gmail.com> <9289a7a28f356e9b27ae2e93f4551a86@stz-bg.com>

* 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