In this PostgreSQL post explains how to use the PostgreSQL GROUP BY clause with syntax and examples.
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.
The syntax for the GROUP BY clause in PostgreSQL is:
The expressions that are not encapsulated within an aggregate function and must be included in the GROUP BY clause.
It can be an aggregate function such as sum, count, min, max, or avg functions.
The tables that you wish to retrieve records from. There must be at least one table listed in the FROM clause.
Optional. The conditions that must be met for the records to be selected.
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).
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.
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'.
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.
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.