Answer the question
In order to leave comments, you need to log in
How to quickly get a random row from a postgresql database?
You need to get a random string from the database.
From what we have now:
Slow:
SELECT * FROM items WHERE sale_price > 100 AND sale_price < 10000 ORDER BY random() LIMIT 1
SELECT * FROM items WHERE sale_price > 100 AND sale_price < 10000 OFFSET floor(random() * (SELECT count(*) FROM items)) LIMIT 1
WITH RECURSIVE r AS (
WITH b AS (
SELECT
min(t.id),
(
SELECT t.id
FROM items AS t
WHERE
t.sale_price > 100 AND
t.sale_price < 10000
ORDER BY t.id DESC
LIMIT 1
OFFSET ${custom.numRows} - 1
) max
FROM items AS t
WHERE
t.sale_price > 100 AND
t.sale_price < 10000
)
(
SELECT
id, min, max, array[]::bigint[] || id AS a, 0 AS n
FROM items AS t, b
WHERE
id >= min + ((max - min) * random())::int AND
t.sale_price > 100 AND
t.sale_price < 10000
LIMIT 1
) UNION ALL (
SELECT t.id, min, max, a || t.id, r.n + 1 AS n
FROM items AS t, r
WHERE
t.id > min + ((max - min) * random())::int AND
t.id <> all( a ) AND
r.n + 1 < ${custom.numRows} AND
t.sale_price > 100 AND
t.sale_price < 10000
LIMIT 1
)
)
SELECT * FROM items AS t, r WHERE r.id = t.id
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question