# PostgreSQL + Rails 3: SELECT AS weirdness

**URL:** <https://www.ruby-forum.com/t/postgresql-rails-3-select-as-weirdness/193989>\
**Category:** Rails\
**Created:** [August 27, 2010, 4:09pm UTC](https://www.ruby-forum.com/t/postgresql-rails-3-select-as-weirdness/193989 "2010-08-27T16:09:18Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![IAmNan](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/i/65b543/32.png) [@IAmNan](https://www.ruby-forum.com/u/IAmNan)\
**Post date:** [August 27, 2010, 4:09pm UTC](https://www.ruby-forum.com/t/postgresql-rails-3-select-as-weirdness/193989/1 "2010-08-27T16:09:18Z")

</div>

Here’s a class function I’ve made in a model called Exchange:  
def self.get\_history(product\_id)  
exchanges = Exchange.select(“product\_id, quantity, week,  
SUM(quantity) AS total”)  
exchanges = exchanges.where(‘product\_id = ?’, product\_id)  
exchanges = exchanges.group(“week”)  
end

This gets me a total number of a particular widget sold by week. It  
worked fine locally on Sqlite3 until I pushed it up to Heroku, which  
uses PostgreSQL.

PostgreSQL complained that I needed to include everything in the  
SELECT clause in the GROUP\_BY. I did a search and sure enough, that’s  
the case. It’s weird, everyone thinks so, but it’s the way life is.  
It’s also weird that the ActiveRecord PostgreSQL adapter wouldn’t do  
this for me. Anyway, I changed the group and it stopped complaining. I  
stopped complaining too.

exchanges = exchanges.group(“week, product\_id, quantity”)

I was back on the road… except… Now “total” is coming back as a  
string, not an integer.

Console output from PostgreSQL:

> Exchange.get\_history(83).last.total  
> =\> “20.25”

Console output from Sqlite3:

> Exchange.get\_history(83).last.total  
> =\> 20.25

What the hey! Does that make seem busted to anyone?

I couldn’t find it documented anywhere so I found a solution purely by  
trial and error. I modified the select:  
exchanges = Exchange.select(“product\_id, week, SUM(quantity) AS  
quantity”)

So the “fix” was changing the AS portion of the SELECT clause. The  
calculated column needs have the same name as the column being  
operated on. Notice I also removed quantity from the list of selected  
columns to avoid a clash.

[Rails 3.0.0.rc2 + Ruby 1.8.7]
