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

HAVING with Complex Expressions

Filter groups using calculations and expressions within the HAVING clause for advanced filtering.

HAVING with Complex Expressions

What you'll learn: How to use calculations, formulas, and multi-layered expressions inside the HAVING clause to perform sophisticated group-level filtering in SQL.

Beyond Simple Aggregate Filters

So far, you've used HAVING to filter groups based on straightforward aggregate comparisons (like HAVING COUNT(*) > 10). But real business questions often require more complex logic. Just like you can perform calculations in SELECT or WHERE, you can build complex expressions inside HAVING—combining multiple aggregates, arithmetic operations, and even conditional logic.

Building Complex HAVING Expressions

You can combine aggregates with math operators:

SELECT product_category, 
       COUNT(*) as order_count,
       AVG(revenue) as avg_revenue
FROM orders
GROUP BY product_category
HAVING AVG(revenue) > SUM(revenue) / COUNT(*) * 1.1;

This filters for categories where average revenue exceeds 110% of a calculated threshold—a complex business rule expressed directly in the filter.

You can also compare multiple aggregates:

SELECT region, 
       SUM(sales) as total_sales,
       COUNT(DISTINCT customer_id) as unique_customers
FROM transactions
GROUP BY region
HAVING SUM(sales) / COUNT(DISTINCT customer_id) > 1000;

Here we're filtering regions where average sales per unique customer exceeds $1,000—using a ratio of two different aggregate functions.

Why This Matters

Complex HAVING expressions let you encode sophisticated business logic without needing separate queries or post-processing. Think of it as setting a "smart filter" that evaluates calculated metrics—like "show me only teams where productivity (tasks/person) exceeds twice the company average."

Key Takeaway: HAVING supports complex expressions combining multiple aggregates, arithmetic, and calculations, enabling powerful group-level filtering based on sophisticated business rules within a single query.