SQL SELECT SUM: Understanding the SUM() Function in SQL
SQL SELECT SUM
The SQL SELECT SUM() function is a strong aggregate function that returns the total sum of a numeric column in a database. It is widely used in data analysis and reporting to get the total value of an expression across multiple records.
Complete Python Course with Advance topics:-Click Here
SQL Tutorial :-Click Here
SQL SUM() Syntax
SELECT SUM(expression)
FROM table_name
WHERE conditions;
- expression: This is the numeric field or formula that needs to be summed.
- table_name: The name of the table from which data is retrieved.
- conditions: (Optional) Specifies which records should be included in the sum calculation.
Example 1: SQL SUM with a Single Column
Let’s consider an employees
table with the following data:
ID | EMPLOYEE_NAME | SALARY |
---|---|---|
1 | RAHUL SHARMA | 45000 |
2 | ANANYA SINGH | 28000 |
3 | VIKRAM PATEL | 39000 |
4 | MEGHA AGRAWAL | 23000 |
Query:
If we want to find the total salary of all employees earning more than 25,000, we can use:
SELECT SUM(salary) AS "Total Salary"
FROM employees
WHERE salary > 25000;
Result:
Total Salary: 112,000
This query returns the total salary of employees who earn more than 25,000 per month.
Example 2: SQL SUM with DISTINCT Values
We can use the DISTINCT
keyword to sum only unique salary values:
SELECT SUM(DISTINCT salary) AS "Total Salary"
FROM employees
WHERE salary > 25000;
This ensures that duplicate salaries are not counted more than once.
Example 3: SQL SUM with GROUP BY
The GROUP BY
statement allows us to calculate the total sales per department.
Consider the following sales_data
table:
ID | DEPARTMENT | DATE | DAILY_SALES |
---|---|---|---|
1 | IT | 2023-07-10 | 500 |
2 | HR | 2023-07-10 | 200 |
3 | IT | 2023-07-11 | 600 |
4 | HR | 2023-07-11 | 300 |
5 | FINANCE | 2023-07-10 | 400 |
Query:
SELECT department, SUM(daily_sales) AS "Total Sales"
FROM sales_data
GROUP BY department;
Result:
DEPARTMENT | TOTAL SALES |
---|---|
IT | 1100 |
HR | 500 |
FINANCE | 400 |
This query groups the sales data by department and calculates the total sales per department.
Download New Real Time Projects :-Click here
Complete Advance AI topics:-Â CLICK HERE
Conclusion
The SQL SUM()
function is a crucial tool for performing aggregate calculations in databases. Whether you are summing individual fields, working with distinct values, or using GROUP BY
for detailed reports, SUM()
simplifies data analysis effectively.
For more SQL insights and tutorials, stay connected with UpdateGadh!
sql sum SELECT multiple columns
sql sum SELECT group by
sql sum SELECT two columns
sql sum SELECT with condition
sql average group by
sql sum SELECT multiple rows
sql sum SELECT if
sql sum SELECT two columns from same table
sql join
select distinct
sql select sum multiple rows
sql select sum example
sql select sum w3schools
Post Comment