SyntaxStudy
Sign Up
MySQL Intermediate 6 min read

Aggregate Functions

Aggregate functions compute a single result from a set of rows. They are used with GROUP BY to summarize data and are fundamental to reporting and analytics queries.

Core Aggregate Functions

  • COUNT(*): Number of rows (including NULLs)
  • COUNT(col): Number of non-NULL values in a column
  • SUM(col): Total of all values
  • AVG(col): Mean of all values
  • MIN(col) / MAX(col): Smallest and largest value
  • GROUP_CONCAT(col): Concatenates values from multiple rows into one string

Using GROUP BY with Aggregates

When you use an aggregate function alongside non-aggregated columns, MySQL requires a GROUP BY clause listing those columns. The HAVING clause (not WHERE) is used to filter groups based on aggregate results.

Example
SELECT
    category,
    COUNT(*) AS total_products,
    SUM(stock) AS total_stock,
    ROUND(AVG(price), 2) AS avg_price,
    MAX(price) AS highest_price,
    GROUP_CONCAT(product_name ORDER BY price DESC SEPARATOR ', ') AS product_list
FROM products
GROUP BY category
HAVING total_products > 5
ORDER BY avg_price DESC;
Pro Tip

Use HAVING to filter on aggregate results; WHERE filters individual rows before aggregation.