✏️ Explanatory Question

What are aggregate functions in MySQL?

👁 10 Views
📘 Detailed Answer
🟢 Easy
💡

Answer with Explanation

Section 4: Operators, Functions & Clauses

27

What are aggregate functions in MySQL?

Level: Intermediate — The core tools for summarizing and reporting on data.

Aggregate functions perform a calculation on a set of rows and return a single summary value. They are most powerful when combined with the GROUP BY clause to produce per-group summaries.

The Five Main Aggregate Functions

  • COUNT(): Counts the number of rows.
  • SUM(): Adds up all values in a numeric column.
  • AVG(): Calculates the average of a numeric column.
  • MIN(): Returns the smallest value.
  • MAX(): Returns the largest value.
Critical rule: Aggregate functions ignore NULL values (except COUNT(*), which counts all rows including those with NULLs). So AVG(salary) skips rows where salary is NULL.

COUNT Variations Explained

Expression What it counts
COUNT(*) All rows, including NULLs
COUNT(column) Non-NULL values in that column
COUNT(DISTINCT column) Unique non-NULL values

Quick Example

-- Basic aggregates on the whole table
SELECT
    COUNT(*)      AS total_employees,
    SUM(salary)   AS total_payroll,
    AVG(salary)   AS average_salary,
    MIN(salary)   AS lowest_salary,
    MAX(salary)   AS highest_salary
FROM employees;

-- Aggregates per group
SELECT dept_id,
       COUNT(*)    AS emp_count,
       AVG(salary) AS avg_salary
FROM employees
GROUP BY dept_id;

-- Count unique departments
SELECT COUNT(DISTINCT dept_id) AS distinct_depts FROM employees;
Interviewer tip: Name the five functions, then score bonus points by explaining that aggregates ignore NULLs — except COUNT(*) — and that COUNT(column) vs COUNT(*) behave differently.