← Back to Chapters

MySQL GROUP BY & HAVING Clause

? MySQL GROUP BY & HAVING Clause

? Quick Overview

GROUP BY groups identical values, while HAVING filters grouped results. They are commonly used with aggregate functions.

? Key Concepts

  • GROUP BY creates summary rows
  • HAVING filters aggregated data
  • Works with COUNT, SUM, AVG, MIN, MAX

? Syntax / Theory

? View Code Example
-- Syntax showing GROUP BY with HAVING
SELECT column1, COUNT(*)
FROM table
WHERE condition
GROUP BY column1
HAVING condition;

? Table Structure

? View Code Example
-- Sample orders table data
order_id | customer_id | amount | order_date
1 | 1 | 100 | 2021-05-10
2 | 2 | 200 | 2021-06-15
3 | 1 | 300 | 2021-07-20
4 | 3 | 400 | 2021-08-25
5 | 1 | 500 | 2021-09-30

⚙️ GROUP BY Example

? View Code Example
-- Calculate total amount per customer
SELECT customer_id, SUM(amount)
FROM orders
GROUP BY customer_id;

? Output Explanation

Each customer is grouped once and their order amounts are summed.

? HAVING Example

? View Code Example
-- Filter grouped results using HAVING
SELECT customer_id, SUM(amount)
FROM orders
GROUP BY customer_id
HAVING SUM(amount) >= 500;

? Use Cases

  • Sales reports by customer or month
  • Finding top-performing products
  • Filtering summary analytics

? Tips & Best Practices

  • Use WHERE before grouping
  • Use HAVING after aggregation
  • Always validate aggregate logic

? Try It Yourself

  • Group orders by month
  • Filter months with sales > 1000
  • Experiment with AVG and COUNT