BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl
Home / SQL / Group By clause in SQL

Group By clause in SQL

By Chaitanya Singh

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.

Posted Under: SQL

Leave a Reply Cancel reply

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

SQL Tutorial

  • SQL Tutorial
  • SQL Introduction
  • SQL Syntax
  • SQL Data Types

SQL Database

  • SQL CREATE DB
  • SQL DROP DB
  • SQL Rename DB
  • SQL USE DB

SQL Queries

  • 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

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap