SQL Group By

SQL GROUP BY Statement

The SQL GROUP BY Statement is used along with the group functions to retrieve data in group based on one or more columns. The GROUP BY statement is used with aggregate functions (COUNT, MAX, MIN, SUM, AVG) to group the resultset by one or more columns.

GROUP BY Syntax

SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);

Example

If you want to know the total amount of salary spent on each department, the query would be like:
SELECT dept, SUM (salary) 
FROM employee 
GROUP BY dept; 
The output would be like:
dept               salary
------------   --------------
Arts               25000
Science            35000
Commerce           35000
Sports             20000
Wrestling          30000
NOTE: The group by clause must contain all the columnd specified in the select list expect those used along with the group functions.

See Example Below:
SELECT name, dept, SUM (salary) 
FROM employee 
GROUP BY name, dept;
The output would be like:
name         dept          salary
---------- ------------  --------
Shahrukh     Arts          25000
Salman       Science       35000
Aamir        Commerce      35000
Tiger        Sports        20000
John         Wrestling     30000

Prev - SQL Group Functions Next - SQL HAVING Clause

Comments