Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

161
Views
Rails fastest way to get table records count

I have a user table in Postgresql database, if run User.count, it takes 150ms to get result. It is too too slow to us. Ideally, it shall take less than 10ms to return me the result. Is there any way to cache sql result in model level? Something like

def self.total_count
  User.count.cached # that's my imagination
end
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

In my opinion, there are several ways you could go about this -

  1. You could have another table that stores the count of the total number of users by incrementing the count there when a user is added/deleted or at frequent time intervals.
  2. If your table is extremely big and accuracy is not the most important thing, you also look into Postgres' COUNT ESTIMATE query.

    SELECT reltuples AS approximate_row_count FROM pg_class WHERE relname = 'users';

over 4 years ago · Santiago Trujillo Report

0

You should look into counter_cache. It will work great if your user belongs_to another model http://guides.rubyonrails.org/association_basics.html

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!