instance method count_by_sql

Ruby on Rails 6.0.6

Since v3.2.22.5

Available in: v3.2.22.5 v4.0.13 v4.1.16 v4.2.9 v5.2.8.1 v6.0.6 v6.1.7.10 v7.0.10 v7.1.6 v7.2.3 v8.0.4 v8.1.2

Signature

count_by_sql(sql)

Returns the result of an SQL statement that should only include a COUNT(*) in the SELECT part. The use of this method should be restricted to complicated SQL queries that can’t be executed using the ActiveRecord::Calculations class methods. Look into those before using this method, as it could lock you into a specific database engine or require a code change to switch database engines.

Product.count_by_sql "SELECT COUNT(*) FROM sales s, customers c WHERE s.customer_id = c.id"
# => 12

Parameters

  • sql - An SQL statement which should return a count query from the database, see the example above.

Parameters

sql req
Source
# File activerecord/lib/active_record/querying.rb, line 78
    def count_by_sql(sql)
      connection.select_value(sanitize_sql(sql), "#{name} Count").to_i
    end

Defined in activerecord/lib/active_record/querying.rb line 78 · View on GitHub · Improve this page · Find usages on GitHub

Defined in ActiveRecord::Querying

Type at least 2 characters to search.

↑↓ navigate · open · esc close