Skip to content
Home Tutorials Roadmaps Courses
Log in Join free
Tutorials MySQL COUNT, SUM, AVG
MySQL Intermediate FREE

COUNT, SUM, AVG

Lesson 1 of 16 Intermediate Interactive

Aggregate functions calculate on sets of rows.

Functions

  • COUNT(*) � all rows
  • COUNT(col) � non-NULL values
  • SUM(), AVG(), MIN(), MAX()

Syntax

MYSQL
SELECT COUNT(*) FROM users;
SELECT COUNT(DISTINCT country) FROM users;
SELECT SUM(total) AS revenue FROM orders WHERE status = "completed";
SELECT AVG(price) AS avg_price FROM products;
SELECT MIN(price), MAX(price) FROM products;
Aggregate Functions
SQL
SELECT
    COUNT(*) AS total_users,
    COUNT(DISTINCT city) AS unique_cities,
    AVG(age) AS avg_age,
    MIN(age) AS youngest,
    MAX(age) AS oldest,
    SUM(score) AS total_score
FROM users;

-- With filter
SELECT COUNT(*) AS adults
FROM users
WHERE age >= 18;

-- Aggregates with CASE
SELECT
    AVG(CASE WHEN gender = "M" THEN score END) AS male_avg,
    AVG(CASE WHEN gender = "F" THEN score END) AS female_avg
FROM users;

Practice

1
Exercise

Total revenue per category.

Answer
SELECT category, SUM(total) AS revenue
FROM orders o JOIN products p ON o.product_id = p.id
WHERE status = "completed"
GROUP BY category;

Quick Quiz

1

COUNT(*) vs COUNT(col)?

COUNT(*) counts all rows; COUNT(col) excludes NULLs.

Interview Questions

No. Use HAVING after GROUP BY to filter aggregated results.