Eroxl's Notes
Aggregate Functions (DML)

Aggregate functions perform calculations on multiple rows and return a single value.

Basic Syntax

SELECT COUNT(*) FROM person;

Count the total number of rows in the person table.

Common Aggregate Functions

  • COUNT() - Counts the number of rows.
  • SUM() - Calculates the sum of values.
  • AVG() - Calculates the average value.
  • MIN() - Finds the minimum value.
  • MAX() - Finds the maximum value.

Examples

SELECT COUNT(*), AVG(grade), MAX(grade), MIN(grade)
FROM student;

Get count, average, maximum, and minimum grades from the student table.

SELECT SUM(salary)
FROM employee
WHERE department = 'Engineering';

Calculate total salary for engineering department.

Grouping Results

Use GROUP BY to group rows and apply aggregate functions to each group:

SELECT course_id, COUNT(*) AS enrollment_count
FROM enrollment
GROUP BY course_id;

Count enrollments for each course.

Having Clause

Use HAVING to filter grouped results (similar to WHERE but for aggregated data):

SELECT course_id, COUNT(*) AS enrollment_count
FROM enrollment
GROUP BY course_id
HAVING COUNT(*) > 10;

Show only courses with more than 10 enrollments.

Difference between WHERE and HAVING:

  • WHERE filters rows before grouping
  • HAVING filters groups after aggregation