Cheat Sheet

MySQL: SQL Aggregate Functions Reference Guide

MySQL guide: Reference for COUNT, SUM, AVG, MIN, MAX and GROUP BY usage.

This guide is specifically for MySQL syntax.

SQL Aggregate Functions Reference Guide

Reference for COUNT, SUM, AVG, MIN, MAX and GROUP BY usage.


COUNT

Syntax:

COUNT(*) | COUNT(column) | COUNT(DISTINCT column)

Counts rows. COUNT(*) includes NULLs, COUNT(column) excludes NULLs.

Example:

SELECT COUNT(*) as total, COUNT(email) as with_email, COUNT(DISTINCT dept) as depts FROM users;

💡 Note: COUNT(1) = COUNT(*)


SUM

Syntax:

SUM(column) | SUM(DISTINCT column)

Adds up numeric values. Ignores NULLs.

Example:

SELECT SUM(amount) as total, SUM(DISTINCT amount) as unique_sum FROM transactions;

💡 Note: Returns NULL if all values are NULL


AVG

Syntax:

AVG(column) | AVG(DISTINCT column)

Calculates arithmetic mean. Ignores NULLs.

Example:

SELECT AVG(salary) as avg_salary, ROUND(AVG(salary), 2) as rounded FROM employees;

💡 Note: Use ROUND() for decimal precision


MIN / MAX

Syntax:

MIN(column) | MAX(column)

Finds minimum or maximum value. Works on numbers, strings, dates.

Example:

SELECT MIN(salary) as lowest, MAX(salary) as highest, MAX(hire_date) as newest FROM employees;

💡 Note: Works with any comparable type


GROUP BY

Syntax:

SELECT columns, AGG() FROM table GROUP BY columns

Groups rows by column values for aggregation.

Example:

SELECT department, AVG(salary) FROM employees GROUP BY department;

💡 Note: Non-aggregated columns must be in GROUP BY


HAVING

Syntax:

SELECT columns, AGG() FROM table GROUP BY columns HAVING condition

Filters groups after aggregation (WHERE filters before).

Example:

SELECT department, COUNT(*) FROM employees GROUP BY department HAVING COUNT(*) > 5;

💡 Note: Can use aggregate functions in HAVING


Quick Reference Table

| Function | Purpose | |----------|---------| | COUNT | Counts rows | | SUM | Adds up numeric values | | AVG | Calculates arithmetic mean | | MIN / MAX | Finds minimum or maximum value | | GROUP BY | Groups rows by column values for aggregation | | HAVING | Filters groups after aggregation (WHERE filters before) |

Related Cheat Sheets

Continue learning with more SQL references:


MySQL-Specific Notes

This page covers MySQL syntax. Other databases may have different syntax for similar operations.

Ready to practice?

Apply what you've learned with hands-on SQL exercises.