SQL Group By

SQL Group By

The SQL GROUP BY is used when at least one of the aggregation functions is used in a select query.
The aggregate functions are: count, max, min, sum, avg.

Group By syntax

SELECT column_name1, column_name2, function(column_name1)
FROM table_name
GROUP BY column_name1, column_name2

Group By example

Coder books table

IDTitlePriceDescription
1Learn SQL20Learn SQL language
2Learn MySQL22Learn MySQL language
3HTML book17Learn HTML
4Learn PHP20Introduction to PHP
5Learn PHP20PHP course
SELECT id, title, price, count(price) p_count
FROM coder_books
GROUP BY id, title, price

Result

IDTitlePricep_count
1Learn SQL201
2Learn MySQL221
3HTML book171
4Learn PHP201
5Learn PHP201
SELECT price, count(price) p_count
FROM coder_books
GROUP BY price
HAVING count(*) > 0

Result

Pricep_count
171
203
221