Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why we use group by in sql

Tags:

sql

group-by

When we make a SQL request like this:

SELECT attr1, attr2, AGGR(*)
  FROM SomeTable
 GROUP BY attr1, attr2

for some aggregate function, we have to include a GROUP BY clause and list attr1 and attr2 in it. My question is: why doesn't the SQL DBMS do it itself?

like image 292
Hunsu Avatar asked Apr 08 '26 18:04

Hunsu


1 Answers

Because you may want to group by attr1, attr2 and attr3, even though you have no interest in the actual attr3 value itself.

In other words, you may be required to group by the non-aggegated columns but this in only at a minimum. There's nothing preventing you from grouping by columns not actually included in the query.

And, since the query evaluator doesn't know what you wanted (or it wants you to follow the relevant standard), it may think it safer to insist you explicitly state it.

like image 167
paxdiablo Avatar answered Apr 11 '26 08:04

paxdiablo



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!