I'm (thoroughly) learning SQL at the moment and came across the GROUP BY
clause.
GROUP BY
aggregates or groups the resultset according to the argument(s) you give it. If you use this clause in a query you can then perform aggregate functions on the resultset to find statistical information on the resultset like finding averages (AVG())
or frequency (COUNT())
.
My question is: is the GROUP BY statement in any way useful without an accompanying aggregate function?
Update
Using GROUP BY
as a synonym for DISTINCT
is (probably) a bad idea because I suspect it is slower.
Using
DISTINCT
would be a synonym in such a situation, but the reason you'd want/have to define aGROUP BY
clause would be in order to be able to defineHAVING
clause details.If you need to define a
HAVING
clause, you have to define aGROUP BY
- you can't do it in conjunction withDISTINCT
.Note: everything below only applies to
MySQL
GROUP BY
is guaranteed to return results in order,DISTINCT
is not.GROUP BY
along withORDER BY NULL
is of same efficiency asDISTINCT
(and implemented in the say way). If there is an index on the field being aggregated (or distinctified), both clauses use loose index scan over this field.In
GROUP BY
, you can return non-grouped and non-aggregated expressions.MySQL
will pick any random values from from the corresponding group to calculate the expression.With
GROUP BY
, you can omit theGROUP BY
expressions from theSELECT
clause. WithDISTINCT
, you can't. Every row returned by aDISTINCT
is guaranteed to be unique.You can perform a DISTINCT select by using a GROUP BY without any AGGREGATES.
Group by can used in Two way Majorly
1)in conjunction with SQL aggregation functions
2)to eliminate duplicate rows from a result set
SO answer to your question lies in second part of USEs above described.
It is used for more then just aggregating functions.
For example, consider the following code:
This will return only 1 result per product, but with the latest updated value of that records.