Aggregate Functions in SQL
? Aggregate Functions in SQL
Aggregate functions perform calculations on a group of rows and return a single value — often used with GROUP BY to summarize data.
? Common Aggregate Functions
| Function | Description |
|---|---|
COUNT() | Counts the number of rows |
SUM() | Adds values in a numeric column |
AVG() | Calculates the average of numeric values |
MIN() | Returns the smallest value |
MAX() | Returns the largest value |
? 1. COUNT()
Counts the number of rows (non-null values if used with a column).
SELECT COUNT(*) FROM employees;SELECT COUNT(salary) FROM employees; -- Ignores NULLs? 2. SUM()
Calculates the total of numeric values.
SELECT SUM(salary) AS total_salary FROM employees;? 3. AVG()
Finds the average of numeric values.
SELECT AVG(salary) AS avg_salary FROM employees;? 4. MIN()
Returns the lowest value.
SELECT MIN(salary) AS min_salary FROM employees;? 5. MAX()
Returns the highest value.
SELECT MAX(salary) AS max_salary FROM employees;? Example with GROUP BY
Assume a table employees with department and salary:
SELECT department, COUNT(*) AS total_employees, AVG(salary) AS avg_salaryFROM employeesGROUP BY department;? This will give one row per department with count and average salary.
? Notes:
All aggregate functions ignore
NULLvalues (exceptCOUNT(*)).Often used with
GROUP BYorHAVING.
? Tip: Use HAVING to Filter Aggregates
SELECT department, AVG(salary)FROM employeesGROUP BY departmentHAVING AVG(salary) > 50000;Let me know if you want practice problems, nested aggregate examples, or window function comparison!