# Find\_by\_sql vs connection.select\_all

**URL:** <https://www.ruby-forum.com/t/find-by-sql-vs-connection-select-all/112036>\
**Category:** Rails\
**Created:** [August 14, 2007, 3:34pm UTC](https://www.ruby-forum.com/t/find-by-sql-vs-connection-select-all/112036 "2007-08-14T15:34:12Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![BowmanS\_Eric\_R](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/dfb087/32.png) [@BowmanS\_Eric\_R](https://www.ruby-forum.com/u/BowmanS_Eric_R)\
**Post date:** [August 14, 2007, 3:34pm UTC](https://www.ruby-forum.com/t/find-by-sql-vs-connection-select-all/112036/1 "2007-08-14T15:34:12Z")

</div>

I was trying to do SUM based mySQL query simliar to the following:

SELECT SUM(updated\_on - created\_on) AS total from signups

If I were to run this command in the mySQL console I would get a  
result. However, if I were to run it using the following command in  
Rails:

Signup.find\_by\_sql(“SELECT SUM(updated\_on - created\_on) AS total from  
signups”)

The query that is written to the log is:

SELECT SUM(updated\_on - created\_on) AS total from signups

Like I said before, if I take that query to the mySQL console, I get  
the expected result, however the result to the view is simply #

NOW, if take the query and put it in with:

Signup.connection.select\_all(“SELECT SUM(updated\_on - created\_on) AS  
total from signups”)

I get the expected result to the view and the same SQL code is written  
to the log

What is the difference then in find\_by\_sql and connection.select\_all

My initial guess is that find\_by\_sql is expecting a normal find(:all)  
based result that follows the model format whereas  
connection.select\_all allows any sort of SQL code and gives the result  
required.

Any thoughts or comments appreciated.

-E

---

<div class="post-metadata">

**Author:** ![BowmanS\_Eric\_R](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/dfb087/32.png) [@BowmanS\_Eric\_R](https://www.ruby-forum.com/u/BowmanS_Eric_R)\
**Post date:** [August 14, 2007, 5:27pm UTC](https://www.ruby-forum.com/t/find-by-sql-vs-connection-select-all/112036/2 "2007-08-14T17:27:29Z")

</div>

I got the same results. How I got the results out of the query was  
the problem. It helps to check the Rails API before posting:)

select\_all and find\_by\_sql returns the result in the following:

“returns an array of record hashes with the column names as keys and  
column values as values.”

So therefore in my query to get the value of the result after I set  
the query to the variable @sum

@sum[0][‘total’]

Since I am looking for just a one result line I will end up using  
select\_one which follows a different slightly different model when  
returning the results:

“Returns a record hash with the column names as keys and column values  
as values.”

When using the existing variable from before, would mean that:

@sum[‘total’]

would give me the desired result.
