# Extended count function for use with queries containing a GR

**URL:** <https://www.ruby-forum.com/t/extended-count-function-for-use-with-queries-containing-a-gr/49237>\
**Category:** Rails\
**Created:** [December 1, 2005, 6:15pm UTC](https://www.ruby-forum.com/t/extended-count-function-for-use-with-queries-containing-a-gr/49237 "2005-12-01T18:15:22Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![rails.list](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/258eb7/32.png) [@rails.list](https://www.ruby-forum.com/u/rails.list)\
**Post date:** [December 1, 2005, 6:15pm UTC](https://www.ruby-forum.com/t/extended-count-function-for-use-with-queries-containing-a-gr/49237/1 "2005-12-01T18:15:22Z")

</div>

Hi everybody.

While playing around with pagination I noticed that when using certain  
GROUP BY clauses Rails would think that your result contains less lines  
than it actually does. This is related to the use of a plain “SELECT  
COUNT(\*)” for getting the number of total rows which the following query  
will return.

In order to bypass this problem, I created the following replacement for  
ActiveRecord::Base.count:  
module ActiveRecord  
class Base  
class \<\< self  
def count(conditions = nil, joins = nil)  
if joins =~ /GROUP BY/  
sql = "SELECT SQL\_CALC\_FOUND\_ROWS \* FROM #{table\_name} "  
sql += joins if joins  
sql += ’ LIMIT 0’  
add\_conditions!(sql, conditions)  
connection.execute(sql)  
sql = ‘SELECT FOUND\_ROWS()’  
else  
sql = "SELECT COUNT(\*) FROM #{table\_name} "  
sql \<\< " #{joins} " if joins  
sql \<\< ‘LIMIT 1’  
add\_conditions!(sql, conditions)  
end  
count\_by\_sql(sql)  
end  
end  
end  
end

As you can see it makes use of the new SQL\_CALC\_FOUND\_ROWS introduced in  
MySQL 4.0. I didn’t upload this as a regular patch to Rails as I guess  
it’s MySQL-specific. Also it doesn’t seem like the most elegant thing to  
do as most likely there will be some overhead in executing the query  
twice even if there won’t be any rows returned the first time.

I had to do this as we have to know how many rows there are in total in  
order to create a paginator. At least I pretty much think so as  
currently it is implemented this way 😉

Is anybody aware of a betterâ?¢ way to do this or similar implementations  
for other RDBMs?

Regards,  
Niels
