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.

API Trace View

How I Cut 22.3 Seconds Off an API Call with Sentry

Struggling with slow API calls? Dan Mindru walks through how he used Sentry's new Trace View feature to shave off 22.3 seconds from an API call.

Get a practical walkthrough of how to identify bottlenecks, split tasks into multiple parallel tasks, identify slow AI model calls, and more.

Read more →

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay