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.

mkyong

Founder of Mkyong.com, passionate Java and open-source technologies. If you enjoy my tutorials, consider making a donation to these charities.

5 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Web Hosting
14 years ago

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

software development company
16 years ago

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

Andrus
17 years ago

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
7 years ago
Reply to  Andrus

True, with huge records it slows down retrieval