The SUM() function in MySQL is an aggregate function that is used to calculate the total sum of a numeric column. It can be useful when you want to get the sum of values in a column, often combined with GROUP BY to summarize data by different categories.
Syntax:
SELECT SUM(column_name)
FROM table_name
WHERE condition;
column_name: The name of the numeric column whose values you want to sum.table_name: The name of the table containing the column.condition: An optionalWHEREclause to filter rows that will be summed.
Example 1: Basic SUM() Usage
To get the total sales from a sales table:
SELECT SUM(sale_amount) AS total_sales
FROM sales;
Example 2: SUM() with GROUP BY
If you want to calculate the total sales for each product category:
SELECT category, SUM(sale_amount) AS total_sales
FROM sales
GROUP BY category;
Example 3: Using SUM() with a WHERE clause
If you want to sum sales for a specific period (e.g., for 2024):
SELECT SUM(sale_amount) AS total_sales
FROM sales
WHERE YEAR(sale_date) = 2024;
Notes:
SUM()ignoresNULLvalues.- It can only be used with numeric columns or expressions.
Let me know if you'd like further examples!
No comments:
Post a Comment