SQL HAVING Function

Quick summary: The SQL HAVING clause filters aggregated results after GROUP BY.

SQL HAVING Syntax

SELECT column, aggregate_function(column) FROM table_name GROUP BY column HAVING aggregate_function(column) condition
SQL

SQL HAVING Basic examples

SELECT status, COUNT(*) FROM orders GROUP BY status HAVING COUNT(*) > 10;
SQL
Output:
Statuses with more than 10 orders

Filters groups based on aggregate conditions.

SQL HAVING Real-world usage

SELECT user_id, SUM(total) AS revenue FROM orders GROUP BY user_id HAVING SUM(total) > 1000;
SQL
Output:
High-value users

Finds users exceeding a revenue threshold.

SQL HAVING Edge cases

SELECT COUNT(*) FROM orders HAVING COUNT(*) > 0;
SQL
Output:
1 row

HAVING can be used without GROUP BY in some databases.

SQL HAVING Common mistakes

Using WHERE instead of HAVING

WHERE cannot filter aggregated values.

Incorrect
WHERE COUNT(*) > 10
Correct
HAVING COUNT(*) > 10

Use HAVING for aggregate filters.

SQL HAVING Frequently Asked Questions

What does HAVING do in SQL?

Filters grouped results.

Difference between WHERE and HAVING?

WHERE filters rows, HAVING filters groups.

Use case of HAVING?

Filtering aggregates.

Syntax?

HAVING condition.

Common mistake?

Using HAVING instead of WHERE.

Used with GROUP BY?

Yes.

Supports aggregates?

Yes.

Performance?

Slower than WHERE.

Handles NULL?

Yes.

Used in reports?

Yes.

Alternative?

Subqueries.

Best practice?

Use WHERE before grouping.

SQL HAVING Related SQL Keywords