Last active
June 15, 2017 20:26
-
-
Save kmayer/48410dae414aef28140d972fa8908f6e to your computer and use it in GitHub Desktop.
How to get a fast, but approximate, row count in ActiveRecord + Postgresql
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
class ApplicationRecord < ActiveRecord::Base | |
self.abstract_class = true | |
class << self | |
def approximate_row_count(table_name = arel_table.name) | |
results = ActiveRecord::Base.connection_pool.with_connection { |c| | |
c.execute("SELECT reltuples::BIGINT AS approximate_row_count FROM pg_class WHERE relname = '#{table_name}'") | |
} | |
results.present? ? results.first['approximate_row_count'].to_i : nil | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
e.g.
MyClass.approximate_row_count
orApplicationRecord.approximate_row_count('my_classes')