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

ID Title Price Description
1 Learn SQL 20 Learn SQL language
2 Learn MySQL 22 Learn MySQL language
3 HTML book 17 Learn HTML
4 Learn PHP 20 Introduction to PHP
5 Learn PHP 20 PHP course
SELECT id, title, price, count(price) p_count
FROM coder_books
GROUP BY id, title, price

Result

ID Title Price p_count
1 Learn SQL 20 1
2 Learn MySQL 22 1
3 HTML book 17 1
4 Learn PHP 20 1
5 Learn PHP 20 1
SELECT price, count(price) p_count
FROM coder_books
GROUP BY price
HAVING count(*) > 0

Result

Price p_count
17 1
20 3
22 1