Skip to content

Instantly share code, notes, and snippets.

@godfat
godfat / query.sql
Last active August 29, 2015 14:22
PostgreSQL fast random rows for tables with integer id with uniform distribution
WITH RECURSIVE results(id, i, picked, roll) AS (
WITH bounds AS (SELECT min(id), max(id) - min(id) AS delta FROM table)
(
SELECT NULL::integer
, 0
, ARRAY[]::integer[]
, min + round(delta * random())
FROM bounds
)
UNION ALL