Skip to content

Instantly share code, notes, and snippets.

@kmayer
Last active June 15, 2017 20:26
Show Gist options
  • Save kmayer/48410dae414aef28140d972fa8908f6e to your computer and use it in GitHub Desktop.
Save kmayer/48410dae414aef28140d972fa8908f6e to your computer and use it in GitHub Desktop.
How to get a fast, but approximate, row count in ActiveRecord + Postgresql
# 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
@kmayer
Copy link
Author

kmayer commented Jun 14, 2017

e.g. MyClass.approximate_row_count or ApplicationRecord.approximate_row_count('my_classes')

@kmayer
Copy link
Author

kmayer commented Jun 15, 2017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment