Note that there are some explanatory texts on larger screens.

plurals
  1. POPostgreSQL GROUP BY different from MySQL?
    primarykey
    data
    text
    <p>I've been migrating some of my MySQL queries to PostgreSQL to use Heroku. Most of my queries work fine, but I keep having a similar recurring error when I use group by:</p> <blockquote> <p>ERROR: column "XYZ" must appear in the GROUP BY clause or be used in an aggregate function</p> </blockquote> <p>Could someone tell me what I'm doing wrong?</p> <p><br> MySQL which works 100%:</p> <pre class="lang-sql prettyprint-override"><code>SELECT `availables`.* FROM `availables` INNER JOIN `rooms` ON `rooms`.id = `availables`.room_id WHERE (rooms.hotel_id = 5056 AND availables.bookdate BETWEEN '2009-11-22' AND '2009-11-24') GROUP BY availables.bookdate ORDER BY availables.updated_at </code></pre> <p><br> PostgreSQL error:</p> <blockquote> <p>ActiveRecord::StatementInvalid: PGError: ERROR: column "availables.id" must appear in the GROUP BY clause or be used in an aggregate function:<br> SELECT "availables".* FROM "availables" INNER JOIN "rooms" ON "rooms".id = "availables".room_id WHERE (rooms.hotel_id = 5056 AND availables.bookdate BETWEEN E'2009-10-21' AND E'2009-10-23') GROUP BY availables.bookdate ORDER BY availables.updated_at</p> </blockquote> <p><br> Ruby code generating the SQL:</p> <pre class="lang-rb prettyprint-override"><code>expiration = Available.find(:all, :joins =&gt; [ :room ], :conditions =&gt; [ "rooms.hotel_id = ? AND availables.bookdate BETWEEN ? AND ?", hostel_id, date.to_s, (date+days-1).to_s ], :group =&gt; 'availables.bookdate', :order =&gt; 'availables.updated_at') </code></pre> <p><br> Expected Output (from working MySQL query):</p> <pre> +-----+-------+-------+------------+---------+---------------+---------------+ | id | price | spots | bookdate | room_id | created_at | updated_at | +-----+-------+-------+------------+---------+---------------+---------------+ | 414 | 38.0 | 1 | 2009-11-22 | 1762 | 2009-11-20... | 2009-11-20... | | 415 | 38.0 | 1 | 2009-11-23 | 1762 | 2009-11-20... | 2009-11-20... | | 416 | 38.0 | 2 | 2009-11-24 | 1762 | 2009-11-20... | 2009-11-20... | +-----+-------+-------+------------+---------+---------------+---------------+ 3 rows in set </pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload