PostgreSQL: SUM Function – Calculate the Total of a Column

Welcome to The Coding College, where we simplify coding for all levels of learners! In this tutorial, we’ll discuss the SUM function in PostgreSQL, a versatile aggregate function for calculating the total of numeric columns in a table.

What is the SUM Function?

The SUM function is used to calculate the total of values in a specified column. It is most commonly applied to numeric data types, such as INTEGER, DECIMAL, or FLOAT.

Syntax

SELECT SUM(column_name)
FROM table_name
[WHERE condition];
  • column_name: The column whose values will be summed.
  • WHERE: (Optional) Filters rows to include in the calculation.

Example: Sample Table

Consider a table named sales:

sale_idproductquantityprice_per_unittotal_price
1Laptop350000150000
2Smartphone530000150000
3Headphones10200020000
4Tablet22500050000

Using the SUM Function

Example 1: Calculate the Total Sales

SELECT SUM(total_price) AS total_sales
FROM sales;

Result:

total_sales
370000

Example 2: Calculate Total Quantity Sold

SELECT SUM(quantity) AS total_quantity
FROM sales;

Result:

total_quantity
20

Using SUM with Conditions

Example 3: Total Sales for Smartphones

SELECT SUM(total_price) AS smartphone_sales
FROM sales
WHERE product = 'Smartphone';

Result:

smartphone_sales
150000

Combining SUM with GROUP BY

Example 4: Total Sales by Product

SELECT product, SUM(total_price) AS product_sales
FROM sales
GROUP BY product;

Result:

productproduct_sales
Laptop150000
Smartphone150000
Headphones20000
Tablet50000

Real-World Applications of SUM

  1. Sales Analysis: Calculate total revenue, total units sold, or other financial metrics.
  2. Inventory Management: Sum up quantities of items in stock.
  3. Expense Tracking: Add up expenses for budget planning.
  4. Performance Metrics: Aggregate scores, hours, or other measurable data.

Learn More at The Coding College

Discover more about PostgreSQL and programming best practices at The Coding College. Our tutorials focus on user benefits and adhere to Google’s E-E-A-T standards for expertise, experience, authority, and trustworthiness.

Conclusion

The PostgreSQL SUM function is a fundamental tool for aggregating numeric data. Whether you’re analyzing sales, inventory, or other metrics, this function provides quick and accurate results.

Stay tuned to The Coding College for more PostgreSQL tutorials and coding tips!

Leave a Comment