2

Hi all, My requirement is simple.I want to select random rows from a table.

For example my table having 10 rows I want to select any three rows randomly.Is there any way in psql.

karthi_ms
  • 5,238
  • 10
  • 36
  • 39

3 Answers3

9

Use the random function.

SELECT * FROM tablename ORDER BY random() LIMIT 3;
coreyward
  • 73,396
  • 19
  • 130
  • 155
Vivek Goel
  • 21,134
  • 28
  • 101
  • 178
4

Please be aware that once your table grows the "order by random/limit" approach will be slow, since it requires a whole table scan.

See http://blog.rhodiumtoad.org.uk/2009/03/08/selecting-random-rows-from-a-table/ for an alternative solution.

Wayne Conrad
  • 96,708
  • 25
  • 150
  • 188
Martin S.
  • 556
  • 4
  • 11
1

Try this !

$ select * from table_name order by random() limit 3 ;
abubacker
  • 4,328
  • 6
  • 31
  • 35