Re: Best way to select a random row from a derived table

From: Condor <condor(at)stz-bg(dot)com>
To: Ryan Murphy <ryanfmurphy(at)gmail(dot)com>
Cc: PostgreSQL mailing lists <pgsql-hackers(at)postgresql(dot)org>, pgsql-general(at)postgresql(dot)org
Subject: Re: Best way to select a random row from a derived table
Date: 2018-01-28 10:09:35
Message-ID: 9289a7a28f356e9b27ae2e93f4551a86@stz-bg.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general pgsql-hackers

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

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Devrim Gündüz 2018-01-28 13:13:32 Re: pgaudit for PostgreSQL 10?
Previous Message Fabien COELHO 2018-01-28 08:17:46 Re: Best way to select a random row from a derived table

Browse pgsql-hackers by date

  From Date Subject
Next Message Petr Jelinek 2018-01-28 16:01:03 Re: [PATCH] Logical decoding of TRUNCATE
Previous Message Fabien COELHO 2018-01-28 08:17:46 Re: Best way to select a random row from a derived table