what is the difference between GROUP BY and ORDER BY in sql

vehomzzz picture vehomzzz · Aug 14, 2009 · Viewed 269.9k times · Source

When do you use which in general? Examples are highly encouraged!

I am referring so MySql, but can't imagine the concept being different on another DBMS

Answer

RiddlerDev picture RiddlerDev · Aug 14, 2009

ORDER BY alters the order in which items are returned.

GROUP BY will aggregate records by the specified columns which allows you to perform aggregation functions on non-grouped columns (such as SUM, COUNT, AVG, etc).

TABLE:
ID NAME
1  Peter
2  John
3  Greg
4  Peter

SELECT *
FROM TABLE
ORDER BY NAME

= 
3 Greg
2 John
1 Peter
4 Peter

SELECT Count(ID), NAME
FROM TABLE
GROUP BY NAME

= 
1 Greg
1 John 
2 Peter

SELECT NAME
FROM TABLE
GROUP BY NAME
HAVING Count(ID) > 1

=
Peter