views:

358

answers:

5

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.

+2  A: 

You can perform a DISTINCT select by using a GROUP BY without any AGGREGATES.

astander
A: 

It is used for more then just aggregating functions.

For example, consider the following code:

SELECT product_name, MAX('last_purchased') FROM products GROUP BY product_name

This will return only 1 result per product, but with the latest updated value of that records.

Am
`MAX()` is an aggregate function.
Max Shawabkeh
@am:Neils is asking about uses without Aggregate function
Sam Rudolph
It doesn't aggregate, it selects a single value from a list. _An aggregate is a collection of items that are gathered together to form a total quantity_
Am
It is an aggregate as it takes a group of values, each from a different row and gives you back a single result - that's the definition of aggregate functions in SQL.
Max Shawabkeh
@Max, accepted as an unfair language difference :), guess i didn't understand correctly the Q.
Am
+1  A: 

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.

Sam Rudolph
+3  A: 

is the GROUP BY statement in any way useful without an accompanying aggregate function?

Using DISTINCT would be a synonym in such a situation, but the reason you'd want/have to define a GROUP BY clause would be in order to be able to define HAVING clause details.

If you need to define a HAVING clause, you have to define a GROUP BY - you can't do it in conjunction with DISTINCT.

OMG Ponies
So your answer is "no", right?
Niels Bom
OMG Ponies
A: 

Note: everything below only applies to MySQL

GROUP BY is guaranteed to return results in order, DISTINCT is not.

GROUP BY along with ORDER BY NULL is of same efficiency as DISTINCT (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 the GROUP BY expressions from the SELECT clause. With DISTINCT, you can't. Every row returned by a DISTINCT is guaranteed to be unique.

Quassnoi