How to get random row from sql query – PostgreSQL

How can i get a random row from a query result in PostgreSQL?
The answer is easy, just using RANDOM() built-in function in PostgreSQL


SELECT scoreid FROM n_score ORDER BY RANDOM() limit 1;

Above example will get a random score id from table n_score. Everytime execute it will get a random score id. Done.

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
3 Comment threads
2 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
5 Comment authors
MiloWeb Hostingsoftware development companymkyongAndrus Recent comment authors
newest oldest most voted
Web Hosting
Guest
Web Hosting

Very nice SELECT, I use it to display random pictures from the database on a website.

software development company
Guest
software development company

simple code but essencial for testing your data
Keep up the good work

Andrus
Guest
Andrus

Just keep in mind that sql own random functions have big speed impact (internally its selecting all rows anyways and picking random one then)…

Milo
Guest
Milo

True, with huge records it slows down retrieval