Reputation: 161
I'm having a table from which I want to select N random rows in PostgreSQL.
However, I don't want to select the whole table, but I want to select random from the rows that respect some constraints (e.g. Price in range, Color = "red" etc.)
I have already seen some ways to do this when id's are generated in a continuous manner. However, in this case, there will be a lot of gaps.
Is there any way of doing this without using order by random() which is to expensive?
Upvotes: 0
Views: 933
Reputation: 728
With postgresql 9.5 you can use
TABLESAMPLE with methods BERNOULLI and SYSTEM
Hier is some good examples and explanations which is better:
Compare different random methods
First install the extension:
CREATE EXTENSION tsm_system_rows;
Try with this:
Select * from your_table tablesample system_rows(1000)
Upvotes: 1