HomeMYSQLWhat are aggregate functions? Give examples.

What are aggregate functions? Give examples.

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:

  1. COUNT() – Returns the number of rows that match a specified condition. SELECT COUNT(*) FROM employees;
  2. SUM() – Returns the total sum of a numeric column. SELECT SUM(salary) FROM employees;
  3. AVG() – Returns the average value of a numeric column. SELECT AVG(salary) FROM employees;
  4. MIN() – Returns the smallest value in a column. SELECT MIN(salary) FROM employees;
  5. MAX() – Returns the largest value in a column. SELECT MAX(salary) FROM employees;
  6. 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 NULL values (except COUNT(*) counts all rows).
  • Often used with GROUP BY to summarize data by categories.
  • Cannot be used directly in WHERE clause; must use HAVING for conditions on aggregated results.

Share: 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *