Skip to main content

SQL GROUP BY Clause

SQL GROUP BY Clause

The GROUP BY clause in SQL is used to group rows that have the same values into summary rows, typically to apply aggregate functions such as COUNT(), SUM(), AVG(), MAX(), or MIN() to each group.


1. Overview

The GROUP BY clause divides the rows returned from a query into groups based on the values of one or more columns. It is often used with aggregate functions to perform calculations on each group separately.

Example:

// Example of using the GROUP BY clause
SELECT department, COUNT(*)
FROM employees
GROUP BY department;

This example groups the rows from the employees table by the department column and calculates the count of employees in each department.


2. Syntax

The basic syntax of the GROUP BY clause is as follows:

SELECT column1, column2, ...
FROM table_name
GROUP BY column1, column2, ...;

The GROUP BY clause must appear after the FROM clause and before the ORDER BY clause, if present.


3. Usage

To use the GROUP BY clause, specify the column(s) to group by after the GROUP BY keyword in an SQL statement. You can also use aggregate functions with the grouped data.

Example:

// Example of using the GROUP BY clause with aggregate functions
SELECT department, COUNT(*), AVG(salary)
FROM employees
GROUP BY department;

This example groups the rows by the department column and calculates the count of employees and the average salary for each department.


4. Conclusion

The SQL GROUP BY clause is a powerful feature for grouping rows in a query based on the values of one or more columns. It enables users to perform aggregate calculations on subsets of data, providing valuable insights into the dataset.

Comments