Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do all columns in a SELECT list have to appear in a GROUP BY clause

Tags:

sql

My lecturer stated:

All column names in SELECT list must appear in GROUP BY clause unless name is used only in an aggregate function

I'm just wanting some confirmation of this as I cannot think of a logical explanation as to why it should be true...

like image 235
user559142 Avatar asked May 13 '11 00:05

user559142


People also ask

Do all SELECT columns need to be in GROUP BY?

Every non aggregate column used in SELECT statement must be added to GROUP BY clause.

Does all columns in the SELECT list must be in the GROUP BY clause apart from the group function?

Answer: D.GROUP BY clause must contain all the columns appearing in the SELECT statement.

Does GROUP BY need to include 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 SELECT column which is not part of GROUP BY?

The direct answer is that you can't. You must select either an aggregate or something that you are grouping by.


1 Answers

Imagine the following:

    A    B    C    Cat   10   False    Dog   25   True    Dog   20   False    Cat   5    False 

If you select A, B and Group By Only A - what would your output be? You'd only have two rows (or tuples) because you have two values for A - but how does it display B?

If you group by A, B, you'd get four rows, no problems there. If you group by A and perform a function on B - like SUM(B) then you get two rows again:

    Cat    15     Dog    45 

But if you select A, B and only group by A - it doesn't know what to do. Truthfully, I believe there are some databases out there that will select a random value for B in that case and I believe there are some that will give you an error message.

like image 75
Rob P. Avatar answered Sep 29 '22 11:09

Rob P.