PostgreSQL – Resolving ‘Column Must Appear in the GROUP BY Clause’ Error

group bypostgresql

I have a table that looks like this:

order_number | key_a | key_b | key_c | key_d | quantity
-------------|-------|-------|-------|------------------
14400        | 2     | 3     | 4     |    54 | 40
14000        | 2     | 3     | 4     |    87 | 13

I'm trying to run the following query:

select order_number,key_a,key_b,key_c,sum(quantity) from my_table
      group by (order_number,key_a,key_b,key_c);

Yet I'm getting the error:

 ERROR:   column "my_table.order_number" must appear in the GROUP BY clause or be used in an aggregate function

Since the column very clearly IS present in the GROUP BY clause,
I am very confused.

I also tried explicitly naming the column as my_table.order_number as shown in the error message, but no dice.

Best Answer

I figured it out. It's the damn parentheses around the columns in the GROUP BY clause. The correct query is:

select order_number,key_a,key_b,key_c,sum(quantity) from my_table
      group by order_number,key_a,key_b,key_c;