Course contentsShow
← Data Science
Lesson 901 of 2,14523. SQL Aggregation and GroupingFree lesson

Multiple Conditions in HAVING

Combine multiple filtering criteria in HAVING using AND, OR, and comparison operators.

Multiple Conditions in HAVING

You'll learn: How to apply multiple filtering rules to grouped aggregates using logical operators in the HAVING clause.

Just as you learned to combine conditions with AND, OR, and NOT in WHERE clauses, you can use the same logical operators in HAVING to create sophisticated filters on aggregated results.

Combining Conditions with AND

When you need all conditions to be true, use AND:

SELECT department, AVG(salary) AS avg_salary, COUNT(*) AS emp_count
FROM employees
GROUP BY department
HAVING AVG(salary) > 50000 AND COUNT(*) >= 5;

This returns only departments where the average salary exceeds $50,000 and there are at least 5 employees.

Combining Conditions with OR

When any condition can satisfy your filter, use OR:

SELECT product_category, SUM(sales) AS total_sales, MAX(price) AS max_price
FROM products
GROUP BY product_category
HAVING SUM(sales) > 100000 OR MAX(price) > 500;

This returns categories with either high total sales or expensive products.

Using Comparison Operators

You can compare aggregates against values or even against each other:

SELECT region, SUM(revenue) AS total_revenue, SUM(cost) AS total_cost
FROM transactions
GROUP BY region
HAVING SUM(revenue) > 500000 AND SUM(revenue) > SUM(cost) * 1.2;

This finds regions where revenue exceeds $500K and is at least 20% higher than costs.

Parentheses for Complex Logic

Just like with WHERE, use parentheses to control evaluation order:

HAVING (COUNT(*) > 10 AND AVG(rating) > 4.0) OR SUM(purchases) > 50000

Key Takeaway: Multiple conditions in HAVING let you filter grouped data with precise, multi-criteria rules using AND, OR, and comparison operators—just remember you're filtering aggregate results, not individual rows.