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,568
  • 11
  • 38
  • 39

3 Answers3

10

Use the random function.

SELECT * FROM tablename ORDER BY random() LIMIT 3;
coreyward
  • 77,547
  • 20
  • 137
  • 166
Vivek Goel
  • 22,942
  • 29
  • 114
  • 186
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
  • 103,207
  • 26
  • 155
  • 191
Martin S.
  • 556
  • 4
  • 11
1

Try this !

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