How Does the SUM() Function Work With the GROUP BY Clause in PostgreSQL

SUM() is an aggregate function in Postgres that helps us find the sum of given numeric values. The SUM() function can be executed with the GROUP BY clause to calculate the sum of a particular column grouped by one or more columns. This process enables users to obtain aggregated results and perform analysis by comparing the sums of different groups.

This post will illustrate the use of the SUM() function alongside the GROUP BY clause in PostgreSQL.

How Does the SUM() Function Work With the GROUP BY Clause in PostgreSQL?

Follow the below-provided syntax to use the SUM() function along with the GROUP BY clause in Postgres:

SELECT col_1, col_2, SUM(col_name)
FROM table_name
GROUP BY col_1, col_2;

In the above syntax, col_1 and col_2 represent the columns of the table, while col_name represents the column to be summed. The col_1 and col_2 columns in the GROUP BY clause determine the criteria by which the table's data will be grouped for the sum calculation.

Example: Using SUM() With GROUP BY

We have a sample table named "emp_bio" that will be used throughout this post:

SELECT * FROM emp_bio;

The following result set shows the data of the “emp_bio” table:

img

In the following snippet, we utilize the SUM() function to calculate the total salary from the “emp_sal” column. After that, the GROUP BY clause is used to group the table’s data according to the employee's salary:

SELECT joining_date, SUM(emp_sal) 
FROM emp_bio
GROUP BY joining_date;

The following snippet demonstrates that the employees’ salary is summed/grouped based on their joining date:

img

In the following snippet, the data of emp_bio table grouped based on the emp_salary column:

SELECT emp_sal, SUM(emp_sal) 
FROM emp_bio
GROUP BY emp_sal;
img

This is how the GROUP BY clause is used with the SUM() function in Postgres.

Conclusion

In PostgreSQL, the SUM() function can be executed with the GROUP BY clause to compute the sum of a particular column grouped by single or multiple columns. By doing so, users can obtain the aggregated results and perform analysis by comparing the sums of different groups. This guide has provided a detailed explanation of how to utilize the SUM() function alongside the GROUP BY clause in PostgreSQL.