SQL - GROUP BY Keyword


Advertisements

Previous Page Next Page

The SQL GROUP BY keyword is used to arrange result table into identical groups with the help of aggregate functions (COUNT, MAX, MIN, SUM, AVG etc). The GROUP BY keyword follows the WHERE clause in a SELECT statement and precedes the ORDER BY keyword.

Syntax

The syntax for using SELECT statement in different scenarios are given below:

SELECT column1, column2
FROM table_name
WHERE condition(s)
GROUP BY column1, column2
ORDER BY column1, column2

Example:

Consider a database table called Employee with the following records:

IDNameCityAgeSalary
1JohnLondon253000
2MarryLondon242750
3JoParis272800
4KimAmsterdam303100
5RameshNew Delhi283000
6SureshNew Delhi282800

  • GROUP BY single column: To find the number of employee present in the Employee table in different age group sorted by Age (descending order), the SQL code is:

    SELECT Age, Count(Name) 
    FROM Employee
    GROUP BY Age
    ORDER BY Age DESC
    

    This will produce the result as shown below:

    AgeCount(Name)
    301
    282
    271
    251
    241

  • GROUP BY multiple columns: To find the average salary of employees present in the Employee table ordered by City and Age, the SQL code is:

    SELECT City, Age, AVG(Salary) 
    FROM Employee
    GROUP BY City, Age
    ORDER BY City, Age
    

    This will produce the result as shown below:

    CityAgeAverage(Salary)
    Amsterdam303100
    London242750
    London253000
    New Delhi282900
    Paris272800


Previous Page Next Page