Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

postgresql 9.3. Group by without all columns

I have a problem with the following query:

SELECT 
        ee.id 
        ee.column2
        ee.column3,
        ee.column4, 
        SUM(ee.column5)
      FROM 
         table1 ee 
         LEFT JOIN table2 epc ON ee.id = epc.id
      WHERE 
         ee.id (6050) 
      GROUP BY ee.id

WHERE column id is the primary key. On version 8.4, the query returns an error saying that column2, column3 and column4 don't exist in the group by clause.

This same query executes successfully on version 9.3.

Does anybody know why?

like image 631
user2514376 Avatar asked Dec 19 '14 08:12

user2514376


People also ask

Does GROUP BY need all columns?

If you specify the GROUP BY clause, columns referenced must be all the columns in the SELECT clause that do not contain an aggregate function. These columns can either be the column, an expression, or the ordinal number in the column list.

Can we use GROUP BY without SELECT?

No, you can GROUP BY a column that was not included in the SELECT statement.

Do you have to GROUP BY all columns in SQL?

Introduction to SQL GROUP BY clause The GROUP BY is an optional clause of the SELECT statement. The GROUP BY clause allows you to group rows based on values of one or more columns.

Can we SELECT column which is not part of GROUP BY?

In MySQL, when you try to select a column that isn't used in the GROUP BY clause, or in an aggregate function inside the statement, it is not a valid statement according to SQL standard and will cause an error.


1 Answers

This was introduced in 9.1

Quote from the release notes:

Allow non-GROUP BY columns in the query target list when the primary key is specified in the GROUP BY clause (Peter Eisentraut)
The SQL standard allows this behavior, and because of the primary key, the result is unambiguous.

It is also explained with examples in the chapter about group by:

In this example, the columns product_id, p.name, and p.price must be in the GROUP BY clause since they are referenced in the query select list (but see below). The column s.units does not have to be in the GROUP BY list since it is only used in an aggregate expression (sum(...)), which represents the sales of a product. For each product, the query returns a summary row about all sales of the product.

In a nutshell: if the group by clause contains a column that uniquely identifies the rows, it is sufficient to include that column only.

like image 53
a_horse_with_no_name Avatar answered Sep 22 '22 07:09

a_horse_with_no_name