0

I am using rails and Postgresql. I have a very large table that includes a column called status. From this status column a lot of rows have a value of 1. I want to select a random row based on all rows with a value of 1 in the status column. Each row also has an id and they are sequential.

What is the fastest way to get this random row?

dimakura
  • 7,575
  • 17
  • 36
user4584963
  • 2,403
  • 7
  • 30
  • 62
  • I would recommend also check this http://stackoverflow.com/questions/8674718/best-way-to-select-random-rows-postgresql for good discussion on how to perform this query effectively – dimakura Sep 12 '15 at 20:34

2 Answers2

0

You can play with OFFSET option

SELECT * FROM users WHERE status = 1 OFFSET random()*I LIMIT 1;

The I is the number of rows in table.

Arsen
  • 10,815
  • 2
  • 34
  • 46
0

Try to use ActiveRecord solution, e.g :

Model_name.where(status: 1).limit(1).order("RANDOM()")

OR :

Model_name.where(status: 1).order("RANDOM()").first

Hope this helps.

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101