Group by clause is used for grouping the similar data after fetching it from tables(s). In this tutorial we will learn how to use GROUP BY clause in SQL.
Syntax
SELECT column_name1, column_name2,... FROM TableName WHERE clause GROUP BY column_namei, column_namej...;
Example
Lets say this is my “EMPLOYEE_DETAILS” table. As you can see it has duplicate rows for several employees.
+---------+----------+-----+-----------+----------+ | S_NO | EMP_NAME | AGE | DEPT | INCOME | +---------+----------+-----+-----------+----------+ | 10001 | Kate | 22 | CSE | 12000 | | 10002 | Kate | 22 | ECE | 13000 | | 10003 | Rick | 33 | ME | 24000 | | 10004 | Rick | 33 | ME | 78000 | | 10005 | Steve | 22 | CSE | 12000 | | 10006 | Mark | 23 | ME | 90000 | | 10007 | Mark | 23 | ME | 45000 | | 10008 | Mark | 23 | ME | 15000 | +---------+----------+-----+-----------+----------+
Suppose if we want to know the total income of each individual employee then I can write the query like this:
SQL> SELECT EMP_NAME, SUM(INCOME) FROM EMPLOYEE_DETAILS GROUP BY EMP_NAME ORDER BY EMP_NAME;
Output:
+----------+----------+ | EMP_NAME | INCOME | +----------+----------+ | Kate | 25000 | | Rick | 102000 | | Steve | 12000 | | Mark | 150000 | +----------+----------+
As you can see we have total income details for each employee as output. This is just an example, you can perform several kind of operations on table using GROUP BY clause.
Leave a Reply