SQL Group By Clause

Group By clause is used with SELECT Statement to get the identical data.
Aggregate function like count(), max(), min(), sum() and avg() are also used Group By clause.

Syntax:-


SELECT column(s)
FROM table_name 
WHERE [condition] 
GROUP By coulumn(s)
ORDER BY column(s)

Example:-Suppose you have an employee table that has 7 records.


+----+------------+-----------+----------------+-----------+
| id | first_name | last_name | email          | country   |
+----+------------+-----------+----------------+-----------+
|  1 | John       | Tailor    | john@abc.com   | USA       |
|  2 | Rom        | Tailor    | rom@abc.com    | USA       |
|  3 | Andrew     | Symonds   | andrew@abc.com | Australia |
|  4 | Miacle     | clerk     | miacle@abc.com | Australia |
|  5 | Sachin     | Tendulkar | sachin@abc.com | India     |
|  6 | Virat      | Kohli     | virat@abc.com  | India     |
|  7 | rohit      | NULL      | rohit@abc.com  | India     |
+----+------------+-----------+----------------+-----------+
Now you want to get the number of employees belongs to each country

SELECT count(id), country from employees GROUP BY country

Output:-


+-----------+-----------+
| count(id) | country   |
+-----------+-----------+
|         2 | Australia |
|         3 | India     |
|         2 | USA       |
+-----------+-----------+
3 rows in set (0.00 sec)