Careeroza
SUM & AVG
The SQL SUM() Function
SUM() returns the total of a numeric column.
Example
Total quantity sold of product 2 (Green Tea):
SELECT SUM(Quantity) AS TotalSold FROM OrderDetails
WHERE ProductID = 2;Result: 1 row
| TotalSold |
|---|
| 15 |
Example (expression)
SUM of an expression: total revenue per line, then overall:
SELECT SUM(od.Quantity * p.Price) AS Revenue
FROM OrderDetails od, Products p
WHERE od.ProductID = p.ProductID;Result: 1 row
| Revenue |
|---|
| 1010.78 |
The SQL AVG() Function
AVG() returns the average value of a numeric column. NULL values are ignored.
Example
The average salary of all employees:
SELECT ROUND(AVG(Salary), 2) AS AvgSalary FROM Employees;Result: 1 row
| AvgSalary |
|---|
| 63833.33 |
Example (above average)
Employees who earn more than the average (uses a subquery):
SELECT FirstName, Salary FROM Employees
WHERE Salary > (SELECT AVG(Salary) FROM Employees);Result: 3 rows
| FirstName | Salary |
|---|---|
| Rahul | 72000 |
| James | 67000 |
| Fatima | 80000 |
AVG and NULL
Example
AVG divides by the number of non-NULL values. To treat NULL as 0, wrap it with COALESCE:
SELECT AVG(Stock) AS AvgIgnoringNull,
AVG(COALESCE(Stock, 0)) AS AvgNullAsZero
FROM Products;Result: 1 row
| AvgIgnoringNull | AvgNullAsZero |
|---|---|
| 109 | 90.8333 |