DEV Community

Malik M
Malik M

Posted on

GROUP BY clause in PostgreSQL

In this tutorial we will learn about the use of GROUP BY clause.
So, let's get started...
It is used to divide the rows in groups that are return from the SELECT statement. You can then apply aggregate functions such as 'SUM()' or 'COUNT()' to each group to find sum or number of items in the groups.

Syntax

SELECT 
   column_1, 
   column_2,
   ...,
   aggregate_function(column_3)
FROM 
   table_name
GROUP BY 
   column_1,
   column_2,
   ...;
Enter fullscreen mode Exit fullscreen mode

The above statement shows the syntax of the 'GROUP BY' clause.
In this syntax, first select the columns that you want to group and apply the aggregate function such as here we can see I have used 'column_1', 'column_2' in the above syntax.
Second list all the columns in the 'GROUP BY' that you want to group.

PostgreSQL evaluates the 'GROUP BY' after the 'FROM' and 'WHERE' clauses but it is evaluated before 'HAVING', 'SELECT', 'DISTINCT', 'ORDER BY' and 'LIMIT' clauses.
This can be seen through the following image:

Image description

Examples
1) GROUP BY without an aggregate function:
We can also use the 'GROUP BY' without using any aggregate function. Let's see an example:

SELECT
   customer_id
FROM
   payment
GROUP BY
   customer_id;
Enter fullscreen mode Exit fullscreen mode

In the above code it gets the data from the 'payment' table and group them by the customer id. Here it acts like distinct and removes all the duplicate results from the set.

Output
Image description

2) GROUP BY with SUM() function:

SELECT
    customer_id,
    SUM (amount)
FROM
    payment
GROUP BY
    customer_id;
Enter fullscreen mode Exit fullscreen mode

To calculate and select the total amount each customer has paid, we can use the 'GROUP BY' clause to first divide the rows in groups in the 'payment' table and then for each group sum the total amount.

Image description

Conclusion:
In this article we learned about 'GROUP BY' clause.

Top comments (0)