Re: How to generate random bigint

From: Thomas Munro <thomas(dot)munro(at)gmail(dot)com>
To: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
Cc: Phillip Diffley <phillip6402(at)gmail(dot)com>, pgsql-general(at)postgresql(dot)org
Subject: Re: How to generate random bigint
Date: 2023-12-21 06:50:11
Message-ID: CA+hUKGKXT12z4rWCUXVXNKWCdwE-hkALhHCczZWdXdtN_htCDw@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Thu, Dec 21, 2023 at 7:21 PM Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us> wrote:
> Phillip Diffley <phillip6402(at)gmail(dot)com> writes:
> > Postgres's random() function generates a random double. That can be
> > converted to a random int for smaller integers, but a double can't
> > represent all of the values in a bigint. Is there a recommended way to
> > generate a random bigint in Postgres?
>
> Doesn't look like there's anything directly exposed for that.
> Since PG v13 you could use gen_random_uuid, if you're careful
> to extract only bits that aren't fixed by the v4 UUID spec.
> pgcrypto's pg_random_bytes() function offers another
> some-assembly-required solution that'd work considerably
> further back. Or you could make a custom C function that
> leverages pg_strong_random().

Also pg_read_binary_file('/dev/urandom', 0, 8) could be useful
(assuming you're on Unix) if you can figure out how to cast it...

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Binaek Sarkar 2023-12-21 08:28:16 Building Extension on Linux fails with relocation error
Previous Message Tom Lane 2023-12-21 06:20:54 Re: How to generate random bigint