Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
I am trying to pull out rows from a postgres database, I can pull them out desc but when I try random I get a Syntax error near random.
Error
PG::Error: ERROR: syntax error at or near "rand"
LINE 1: ... "hashtags".* FROM "hashtags" ORDER BY tweet_id rand LIMIT...
: SELECT "hashtags".* FROM "hashtags" ORDER BY tweet_id rand LIMIT 4
Code to pull it out
<div id="hashtags">
<% Hashtag.order("tweet_id desc").limit(4).each do |hashtag| %>
<blockquote><%= hashtag.content %></blockquote>
<div class="from">— @<%= hashtag.screen_name %></div>
<% end %>
–
–
To fetch random entries from your database you have a few options. Here's a couple
1st approach
This will take 4 random entries out of your DB using SQL.
Hashtag.order("RANDOM()").limit(4)
2nd approach:
You can also use ActiveRecord sample() method to retrieve 4 random rows.
Hashtag.all.sample(4)
As of speed and efficiency; I made a mini-benchmark and tested two commands on my own db (contains 500 records).
The first approach (as expected) was more than twice faster than the second approach.
SQL: 1.8ms
Sample Method: 4.2ms
–
–
–
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.