Aggregate functions in MySQL allow us to perform calculations on a set of values to return a single result. These functions are especially useful in data analysis, as they allow us to calculate sums, averages, count records, and find extreme values. They are commonly used in combination with the GROUP BY clause.
Counts the total number of all employees in the table.
SELECT COUNT(*) AS employee_count FROM employees;
Displays the number of employees in each department.
SELECT department, COUNT(*) AS employee_count FROM employees GROUP BY department;
Calculates the average salary for each individual department.
SELECT department, AVG(salary) AS average_salary FROM employees GROUP BY department;
Displays the number of employees, lowest salary, highest salary, and average salary for each department.
SELECT department, COUNT(*) AS employee_count, MIN(salary) AS lowest_salary, MAX(salary) AS highest_salary, AVG(salary) AS average_salary FROM employees GROUP BY department;
Displays all data about employees who have a salary higher than €1900.
SELECT * FROM employees WHERE salary > 1900;
Counts the number of employees in the Production department.
SELECT COUNT(*) AS total FROM employees WHERE department = 'Production';
Displays a list of all distinct departments in the company, without repetition.
SELECT DISTINCT department FROM employees;
Counts the number of distinct departments in the company.
SELECT COUNT(DISTINCT department) AS department_count FROM employees;
Aggregate functions in MySQL process multiple values from various rows into a single summary result. They are heavily utilized for statistics, generating reports, and data analysis, usually in combination with the GROUP BY clause.
| Name / Function | Description and Behavior | Syntax (HTML) | Simulator Example |
|---|---|---|---|
| COUNT() | Counts the total number of rows within each group (ignores NULL values). | COUNT(column) |
SELECT department, COUNT(*) FROM employees GROUP BY department; |
| SUM() | Calculates and returns the collective sum of numeric values for each specific group. | SUM(column) |
SELECT department, SUM(salary) FROM employees GROUP BY department; |
| AVG() | Calculates the mathematical average value of the numbers within each group. | AVG(column) |
SELECT department, AVG(salary) FROM employees GROUP BY department; |
| MIN() | Finds and returns the lowest (minimum) value found within each separate group. | MIN(column) |
SELECT department, MIN(salary) FROM employees GROUP BY department; |
| MAX() | Finds and returns the highest (maximum) value found within each separate group. | MAX(column) |
SELECT department, MAX(salary) FROM employees GROUP BY department; |
| GROUP_CONCAT() | Combines text values from multiple rows into a single, comma-separated text string per group. | GROUP_CONCAT(column) |
SELECT department, GROUP_CONCAT(first_name) FROM employees GROUP BY department; |