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_id | product | quantity | price_per_unit | total_price |
---|---|---|---|---|
1 | Laptop | 3 | 50000 | 150000 |
2 | Smartphone | 5 | 30000 | 150000 |
3 | Headphones | 10 | 2000 | 20000 |
4 | Tablet | 2 | 25000 | 50000 |
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:
product | product_sales |
---|---|
Laptop | 150000 |
Smartphone | 150000 |
Headphones | 20000 |
Tablet | 50000 |
Real-World Applications of SUM
- Sales Analysis: Calculate total revenue, total units sold, or other financial metrics.
- Inventory Management: Sum up quantities of items in stock.
- Expense Tracking: Add up expenses for budget planning.
- 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!