, , , .
, :
CREATE TABLE test (a int)
0 4 (random() * 5)::int, .
WITH RECURSIVE rand (i, r, is_new) AS (
SELECT
0,
null,
false
UNION ALL
SELECT
i + 1,
next_number.v,
NOT EXISTS (SELECT 1 FROM test WHERE test.a = next_number.v)
FROM
rand r,
(VALUES ((random() * 5)::int)) next_number(v)
WHERE i < 500
)
SELECT * FROM rand WHERE rand.is_new LIMIT 1
I'm not super sure, but PostgreSQL should be able to stop iterating when it has one result, since it knows that the query has a limit of 1.
The good thing about this query is that you can replace (random() * 5)::intwith any identifier generation function you want
source
share