The SQL SUM function aggregates and calculates the total sum of a specified numeric field or formula within a dataset. Its syntax is simple yet powerful.
SELECT SUM(expression)
FROM tables
WHERE conditions;
The 'expression' can be a numerical field or a formula, allowing for flexible application.
Let's go through real-world examples to understand the core concept of the SQL SUM function.
We need to find the total salary of employees earning over $10,000 per month. The query would be something like this:
SELECT SUM(salary) AS "Total Salary"
FROM employee_details
WHERE salary > 120000;
This demonstrates the function's simplicity and efficiency in handling real-world scenarios.
The SQL DISTINCT clause can be combined with the SQL SUM function to calculate the total salary for distinct values above $10,000.
SELECT SUM(DISTINCT salary) AS "Total Salary"
FROM employee_details
WHERE salary > 10000;
This opens up new possibilities in data analysis and presentation
To perform a detailed analysis, we can utilize the SQL GROUP BY statement. This allows us to determine the total sales for each department.
SELECT department, SUM(sales) AS "Total Sales"
FROM order_details
GROUP BY department;
The SQL SUM function is versatile in handling grouped data, offering a comprehensive view of department-wise sales.
This command instructs SQL to count the number of entries in the specified column_name within the table_name.