title: rails/activerecord: how to get SQL COUNT and SUM to work with Postgres (at heroku)
body: <p>My rails 3 app needs to use a SELECT DISTINCT which (as far as I know) cannot be done with activerecord queries. So I have been executing direct SQL and it is running fine locally on sqllite -- But it is failing at Heroku (postgres).</p>
  
  <p>In my local (sqllite) app, this works fine:</p>
  
  <pre><code>r = ActiveRecord::Base.connection.execute("my query string")
  </code></pre>
  
  <p>But on heroku, using ActiveRecord::Base.connection.execute ALWAYS returns an empty dataset </p>
  
  <pre><code>#&lt;PGresult:0x0000000xxxxxxxxx&gt;
  </code></pre>
  
  <p>even for very simple queries such as  </p>
  
  <pre><code>r = ActiveRecord::Base.connection.execute("SELECT numeric_score  FROM beeps WHERE store_id = '132' AND survey_num = '2'")
  </code></pre>
  
  <p>So I'm using <code>heroku console</code> to debug some very basic SQL queries to try to understand how to re-format my SQL to work at Heroku/Postgres.</p>
  
  <p>SELECT column_name WORKS: the heroku console, selecting postgres records is no problem, for example this works fine:</p>
  
  <pre><code>n = Beep.find_by_sql("SELECT numeric_score  FROM beeps WHERE store_id = '132' AND survey_num = '2'")
  </code></pre>
  
  <p>gives the three values expected: </p>
  
  <pre><code>[#&lt;Beep numeric_score: 10&gt;, #&lt;Beep numeric_score: 9&gt;, #&lt;Beep numeric_score: 8&gt;]
  </code></pre>
  
  <p>But <code>SELECT COUNT</code> fails?? When I try to COUNT them in the SQL</p>
  
  <pre><code>n = Beep.find_by_sql("SELECT COUNT(*)  FROM beeps WHERE store_id = '132' AND survey_num = '2'")
  </code></pre>
  
  <p>it fails, giving: </p>
  
  <pre><code>[#&lt;Beep &gt;]
  </code></pre>
  
  <p>And <code>SELECT SUM(column)</code> fails too?? When I try to SUM them</p>
  
  <pre><code>n = Beep.find_by_sql("SELECT SUM(numeric_score)  FROM beeps WHERE store_id = '132' AND survey_num = '2'")
  </code></pre>
  
  <p>it also fails, giving: </p>
  
  <pre><code>[#&lt;Beep &gt;]
  </code></pre>
  
  <p>How do I execute direct SQL with Postgres... SUM(columnname) and COUNT(*) should work, right?</p>