DEV Community

Malik M
Malik M

Posted on

Finding COUNT, SUM, and AVG in PostgreSQL

In this tutorial, I will be explaining how can we find the count, sum and average in PostgreSQL query.
Let's get started...

Finding Count of rows
In this section we will explore how can we find the count of rows.
The COUNT() function returns the number of rows that matches a specified criteria.

Syntax

SELECT COUNT(column_name)
FROM table_name;
Enter fullscreen mode Exit fullscreen mode

Let's understand by an example:
Suppose we want to find the number of customers from the London in our Customer table.

SELECT COUNT(customer_id)
FROM customers
WHERE city = 'London';
Enter fullscreen mode Exit fullscreen mode

The above query first find the rows which satisfies the WHERE clause condition. Then counts the total number of rows and returns a number.

OUTPUT

Image description

Finding SUM
In this section we will explore how can we use SUM() function.
The SUM() function returns the total sum of a numeric column.

Syntax

SELECT SUM(column_name)
FROM table_name;
Enter fullscreen mode Exit fullscreen mode

Let's understand by an example:
Suppose we want to find the the sum of the quantity fields in the order_details table:

SELECT SUM(quantity)
FROM order_details;
Enter fullscreen mode Exit fullscreen mode

The above query returns the total number of items which are in ordered table.

OUTPUT

Image description

Finding AVG
In this section we will explore how can we use AVG() function.
The AVG() function returns the average value of a numeric column.

Syntax

SELECT AVG(column_name)
FROM table_name;
Enter fullscreen mode Exit fullscreen mode

Let's understand by an example:
Suppose we want to find the the average price of all the products in the product table:

SELECT AVG(price)
FROM products;
Enter fullscreen mode Exit fullscreen mode

The above query returns the average price of all the products

OUTPUT

Image description

Conclusion
In this table we learnt about how we can use Count, SUM and AVG in a query.

Top comments (0)