Postgresql Group By Clause

PostgreSQL: GROUP BY Clause

In this PostgreSQL post explains how to use the PostgreSQL GROUP BY clause with syntax and examples.

Description

The PostgreSQL GROUP BY clause is used in a SELECT statement to collect data across multiple records and group the results by one or more columns.

Syntax

The syntax for the GROUP BY clause in PostgreSQL is:

SELECT expression1, expression2, ... expression_n, 
       aggregate_function (expression)
FROM tables
[WHERE conditions]
GROUP BY expression1, expression2, ... expression_n;

Parameters or Arguments

expression1, expression2, ... expression_n

The expressions that are not encapsulated within an aggregate function and must be included in the GROUP BY clause.

aggregate_function

It can be an aggregate function such as sum, count, min, max, or avg functions.

tables

The tables that you wish to retrieve records from. There must be at least one table listed in the FROM clause.

WHERE conditions

Optional. The conditions that must be met for the records to be selected.

Example - Using sum function

Let's look at a PostgreSQL GROUP BY query example that uses the sum function.

This PostgreSQL GROUP BY example uses the sum function to return the name of the department and the total salaries (for the department).

SELECT department, sum(salary) AS "Salaries for department"
FROM employees
GROUP BY department;

Because you have listed one column (the department field) in your SELECT statement that is not encapsulated in the sum function, you must use the GROUP BY clause. The department field must, therefore, be listed in the GROUP BY clause.

Example - Using count function

Let's look at how we could use the GROUP BY clause with the count function.

This GROUP BY example uses the count function to return the department and the number of employees (for that department) that have a status of 'Active'.

SELECT department, count(*) AS "Number of employees"
FROM employees
WHERE status = 'Active'
GROUP BY department;

Example - Using min function

Let's next look at how we could use the GROUP BY clause with the min function.

This GROUP BY example uses the min function to return the name of each department and the minimum salary in the department.

SELECT department, min(salary) AS "Lowest salary"
FROM employees
GROUP BY department;

Example - Using max function

Finally, let's look at how we could use the GROUP BY clause with the max function.

This GROUP BY example uses the max function to return the name of each department and the maximum salary in the department.

SELECT department, max(salary) AS "Highest salary"
FROM employees
GROUP BY department;