← Back to Chapters

MySQL HAVING

?️ MySQL HAVING

? Quick Overview

The HAVING clause filters grouped rows produced by GROUP BY. While WHERE filters individual rows before grouping, HAVING filters groups after aggregation.

? Key Concepts

  • Grouping: Use GROUP BY to aggregate rows into groups.
  • Aggregate functions: SUM(), AVG(), COUNT(), MAX(), MIN().
  • HAVING vs WHERE: WHERE filters rows before aggregation; HAVING filters after aggregation.
  • Placement: HAVING comes after GROUP BY (and after ORDER BY if present).

? Syntax / Theory

? View Code Example
-- Syntax for HAVING: filter grouped results using aggregate conditions
SELECT column1, AGGREGATE_FUNCTION(column2)
FROM table
GROUP BY column1
HAVING condition;

? Code Examples

? View Code Example
-- Get departments with an average salary greater than 50000
SELECT department, AVG(salary)
FROM employees
GROUP BY department
HAVING AVG(salary) > 50000;
? View Code Example
-- Get products with total sales greater than 1000
SELECT product_name, SUM(sales)
FROM products
GROUP BY product_name
HAVING SUM(sales) > 1000;
? View Code Example
-- Example: combining WHERE and HAVING: filter rows then filter groups
SELECT customer_id, SUM(amount) AS total_spent
FROM orders
WHERE status = 'completed'
GROUP BY customer_id
HAVING SUM(amount) > 5000;

? Live Output / Explanation

How it works

1. Filtering rows: Any WHERE clause is applied first to reduce rows.

2. Grouping: Rows are grouped by the columns in GROUP BY.

3. Aggregation: Aggregate functions compute values per group (e.g., SUM, AVG).

4. Filtering groups: HAVING evaluates conditions against those aggregated values and keeps groups that satisfy them.

Example explanation: the query HAVING AVG(salary) > 50000 keeps only departments whose average salary exceeds 50000.

✅ Tips & Best Practices

  • Use HAVING only when you need to filter by aggregated values.
  • Prefer WHERE to filter rows before aggregation for performance reasons.
  • Include non-aggregated columns in GROUP BY to avoid errors and ensure predictable results.
  • When possible, compute heavy filters in WHERE and use HAVING sparingly.

? Try It Yourself

  • Write a query to find customers who have made total purchases greater than $5000 using HAVING.
  • Find departments with an average salary above $40000 (modify the example above).
  • Use multiple conditions in HAVING (e.g., HAVING COUNT(*) > 5 AND AVG(rating) > 4).