Aggregate functions in SQL (and MySQL) are functions that perform a calculation on a set of values and return a single summarized value. They are commonly used with the GROUP BY clause to perform operations on groups of rows, but they can also be used on the whole table.
Common Aggregate Functions in MySQL:
COUNT()– Returns the number of rows that match a specified condition.SELECT COUNT(*) FROM employees;SUM()– Returns the total sum of a numeric column.SELECT SUM(salary) FROM employees;AVG()– Returns the average value of a numeric column.SELECT AVG(salary) FROM employees;MIN()– Returns the smallest value in a column.SELECT MIN(salary) FROM employees;MAX()– Returns the largest value in a column.SELECT MAX(salary) FROM employees;GROUP_CONCAT()– Returns a concatenated string of values from a group.SELECT department_id, GROUP_CONCAT(employee_name) FROM employees GROUP BY department_id;
Key Points:
- Aggregate functions ignore
NULLvalues (exceptCOUNT(*)counts all rows). - Often used with
GROUP BYto summarize data by categories. - Cannot be used directly in
WHEREclause; must useHAVINGfor conditions on aggregated results.
