Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 351
new2cpp Avatar asked Feb 04 '23 14:02

new2cpp


1 Answers

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';

like image 164
Michael Victor Avatar answered Feb 17 '23 21:02

Michael Victor