MYSQL Tutorial



MySQL AGGREGATIONS


MySQL Aggregation Functions

Aggregation functions perform calculations on sets of rows and return a single summary value. They’re often used with GROUP BY to summarize data by categories.

Common Aggregation Functions

Function Description Example
COUNT() Count rows or non-NULL values COUNT(*), COUNT(column)
SUM() Sum of numeric column SUM(amount)
AVG() Average of numeric column AVG(score)
MIN() Minimum value MIN(price)
MAX() Maximum value MAX(date)
GROUP_CONCAT() Concatenate values from a group GROUP_CONCAT(name)
COUNT(DISTINCT) Count unique values COUNT(DISTINCT user_id)

Basic Usage

SELECT
  COUNT(*)      AS total_orders,
  SUM(amount)   AS total_amount,
  AVG(amount)   AS avg_amount,
  MIN(amount)   AS smallest_order,
  MAX(amount)   AS largest_order
FROM orders;
  

Grouped Aggregation

SELECT
  customer_id,
  COUNT(*)        AS orders_count,
  SUM(amount)     AS total_spent,
  AVG(amount)     AS avg_spent
FROM orders
GROUP BY customer_id
ORDER BY total_spent DESC;
  

Filtering Groups with HAVING

SELECT
  department,
  COUNT(*)   AS emp_count,
  AVG(salary) AS avg_salary
FROM employees
GROUP BY department
HAVING AVG(salary) > 60000;
  

Tips & Best Practices

  • Combine multiple aggregates in one SELECT to get a broad summary.
  • Use COUNT(DISTINCT ...) to count unique entries.
  • Remember that GROUP BY groups non-aggregated columns only.
  • Apply HAVING for post-aggregation filtering, and WHERE for pre-aggregation.
  • Aggregate on indexed columns when possible for better performance.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review