SQL GROUP BY - The Coding Shala

Home >> Learn SQL >> SQL GROUP BY

SQL GROUP BY

The SQL 'Group By' is used to arrange identical data into groups. It is often used with aggregate functions (COUNT, MAX, MIN, SUM, AVG) to group the result-set by one or more columns.
SQL GROUP BY - The Coding Shala

SQL GROUP BY SYNTAX

The basic syntax of SQL GROUP BY is as follows - 

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

SQL GROUP BY EXAMPLE 

The following 'EMP' table will be used for the examples - 

Id     Name     Age     Address     Salary  
 1     Akshay     22     Pune        40000  
 2     Mohit      21     Delhi       42000  
 3     Akash      21     Delhi       45000  
 4     Nikhil     24     Mumbai       50000  
 5     Smith      24     Pune        50000  
 6     Akshay      22     Pune       50000  
 7     Nikhil     24     Mumbai      43000 

Now if we want to calculate the total salary of each person then we will apply 'Group By' on the 'Name' column, there are two records with the same name 'Akshay' and 'Nikhil'. The following query will return each person's total salary - 

SQL >> select Name, sum(Salary)  
        from emp  
       group by Name;   
 
Output >>  
 Name     sum(Salary)  
 Akash       45000  
 Akshay      90000  
 Mohit       42000  
 Nikhil      93000  
 Smith       50000

like this, we can get the total salary for each address - 

SQL >> select Address, sum(Salary)  
        from emp  
        group by Address;  
 
Output >>  
 Address     sum(Salary)  
 Delhi       87000  
 Mumbai      93000  
 Pune        140000



Other Posts You May Like
Prev<< SQL Distinct Keyword                                                                     NEXT >>SQL ORDER BY
Please leave a comment below if you like this post or found some error, it will help me to improve my content.

Comments

Popular Posts from this Blog

Java Program to Convert Binary to Decimal - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

N-th Tribonacci Number Solution - The Coding Shala

LeetCode - Shuffle the Array Solution - The Coding Shala

Java Program to Find GCD or HCF of Two Numbers - The Coding Shala