Group By Clause

In SQL, The Group By statement is used for organizing similar data into groups. 
The data is further organized with the help of equivalent function. 
It means, if different rows in a precise column have the same values, it will arrange those rows in a group.
  • The SELECT statement is used with the GROUP BY clause in the SQL query.
  • WHERE clause is placed before the GROUP BY clause in SQL.
  • ORDER BY clause is placed after the GROUP BY clause in SQL.

==================================================================

Let's look at how to use the GROUP BY clause with the SUM function in SQL.

 

employee_number

last_name

first_name

salary

dept_id

1001

Smith

John

62000

500

1002

Anderson

Jane

57500

500

1003

Everest

Brad

71000

501

1004

Horvath

Jack

42000

501


SELECT dept_id, SUM(salary) AS total_salaries
FROM employees
GROUP BY dept_id;

There will be 2 records selected. These are the results that you should see:

 

dept_id

total_salaries

500

119500

501

113000


=========================================================================

GROUP BY with the MIN function

employee_number

last_name

first_name

salary

dept_id

1001

Smith

John

62000

500

1002

Anderson

Jane

57500

500

1003

Everest

Brad

71000

501

1004

Horvath

Jack

42000

501

 

SELECT dept_id, MIN(salary) AS lowest_salary

FROM employees

GROUP BY dept_id;

 

There will be 2 records selected. These are the results that you should see:

 

dept_id

lowest_salary

500

57500

501

42000

 

Points:

  • The GROUP BY Clause is used to group the rows, which have the same values.
  • The SELECT statement in SQL is used with the GROUP BY clause.
  • In the Group BY clause, the SELECT statement can use constants, aggregate functions, expressions, and column names.
  • The GROUP BY Clause is called when the HAVING clause is used to reduce the results.