Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding GROUP BY clause

SELECT a,b from <table_name> GROUP BY a,b,c.

Is the above a valid sql statement?

like image 241
siddarthforever Avatar asked Mar 04 '26 06:03

siddarthforever


2 Answers

Not without a table name it is not. If it had a table name it would be valid, but probably not very useful.

Typically one would use GROUP BY clauses in conjunction with some aggregate function (SUM, COUNT, MAX, MIN, etc.) to derive some values related to the grouped fields.

like image 156
Mike Brant Avatar answered Mar 06 '26 19:03

Mike Brant


Yes, that query is legal SQL. Whether it's useful SQL is another matter entirely.

The query

select a , b
from foo
group by a,b,c

Does the following:

  • groups the rows from the source table into distinct groups, 1 for each unique combination of columns a, b and c.
  • Each such group is then collapsed into a single row containing the grouping columns and the values of any required aggregate functions required by the query.
  • The resulting result set is then returned to the caller, tossing any unwanted columns (in this case, column c).

Since one of the grouping columns is discarded, the specified query is not guaranteed to be a set of unique rows. It might well contain duplicates. For instance, if group by came up with these groups to be returned:

A  B  C
-  -  -
0  0  0
0  0  1
0  1  0
0  1  1
1  0  0
1  0  1
1  1  0
1  1  1

The results set returned by the query would be

A  B
-  -
0  0
0  0
0  1
0  1
1  0
1  0
1  1
1  1

And so, not necessarily useful.

like image 22
Nicholas Carey Avatar answered Mar 06 '26 18:03

Nicholas Carey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!