beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
    • Learn jQuery
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

Group By clause in SQL

By Chaitanya Singh | Filed Under: SQL

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 Cancel reply

Your email address will not be published. Required fields are marked *

SQL Tutorial

  • SQL Introduction
  • SQL Syntax
  • SQL Select
  • SQL Select Distinct
  • SQL Select Count
  • SQL Select Top
  • SQL Where
  • SQL AND, OR & NOT
  • SQL Order By
  • SQL Insert Into
  • SQL Insert Into SELECT
  • SQL Select Random
  • SQL Alias
  • SQL NULL Check
  • SQL Update
  • SQL Delete
  • SQL MIN, MAX
  • SQL SUM
  • SQL AVG

Recently Added..

  • JSON Tutorial
  • Java Regular Expressions Tutorial
  • Java Enum Tutorial
  • Java Annotations Tutorial

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap