Group By

SQL GROUP BY

The GROUP BY is used when aggregate functions exists in the select.
The aggregate functions are: count, max, min, sum, avg.

Syntax

SELECT name_of_column, function(name_of_column)
FROM name_of_table
GROUP BY name_of_column

Example

Orders

ID NAME PRICE
1 Learn Python 45
2 MySQL Tutorial 32
3 PHP examples 24
4 Learn SQL 32
2 MySQL Tutorial 32
SELECT id, name, SUM(price) as total 
FROM orders
GROUP BY id, name
ORDER BY total desc;

Output

ID NAME TOTAL
2 MySQL Tutorial 64
1 Learn Python 45
4 Learn SQL 32
3 PHP examples 24