PostgreSQL GROUP BY clause divides rows into categories based on one or more column values, making it easier to calculate summary information for each category.
- Creates separate result sets for each category.
- Works with aggregate functions like COUNT(), SUM(), AVG(), MIN() and MAX().
Syntax
SELECT column_1, aggregate_function(column2)
FROM table_name
GROUP BY column_1;
Where:
- GROUP BY: Groups rows with the same values into a single group.
- aggregate_function(): Performs calculations such as COUNT(), SUM(), AVG(), MIN() or MAX() on each group.
Examples
Consider the following sales table for the examples below:

Example 1: Group Rows Without an Aggregate Function
Query:
SELECT region
FROM sales
GROUP BY region
ORDER BY region;
Output:

- GROUP BY clause groups rows by the region column and returns one row for each unique region.
Example 2: Calculate Total sales for Each region
Query:
SELECT region,
SUM(amount) AS total_sales
FROM sales
GROUP BY region
ORDER BY total_sales DESC;
Output:

- GROUP BY clause groups the rows by region and the SUM() function calculates the total sales amount for each region.
Example 3: Count the Number of sales by Each sales_person
Query:
SELECT sales_person,
COUNT(*) AS total_sales
FROM sales
GROUP BY sales_person
ORDER BY sales_person;
Output:

- COUNT() function counts the number of sales made by each sales_person after grouping the rows by sales_person.
Example 4: Group by Multiple Columns
Query:
SELECT region,
sales_person,
SUM(amount) AS total_sales
FROM sales
GROUP BY region, sales_person
ORDER BY region;
Output:

- GROUP BY clause groups rows based on both region and sales_person.
- SUM() calculates the total sales for each group.