SQL Having

HAVING filters grouped results after aggregation. It is used together with GROUP BY.

On this page

SQL HAVING Clause

The HAVING clause is used to filter grouped results. Unlike WHERE, which filters rows before grouping, HAVING filters groups after aggregation.

Basic Syntax

SELECT column_name, AGGREGATE_FUNCTION(column_name)
FROM table_name
GROUP BY column_name
HAVING condition;

Example: Countries with More Than 5 Customers

SELECT country, COUNT(*) AS total_customers
FROM customers
GROUP BY country
HAVING COUNT(*) > 5;

WHERE vs HAVING

  • WHERE filters rows before grouping
  • HAVING filters groups after aggregation

Example: WHERE and HAVING Together

First filter active customers, then show only countries with more than 3 active customers:

SELECT country, COUNT(*) AS total_active
FROM customers
WHERE status = 'active'
GROUP BY country
HAVING COUNT(*) > 3;

Using HAVING with SUM

SELECT category, SUM(price * quantity) AS total_sales
FROM order_items
GROUP BY category
HAVING total_sales > 10000;

Common Mistakes

  • Trying to use WHERE with aggregate functions
  • Forgetting GROUP BY when using HAVING
  • Misunderstanding the order of execution

Execution Order Reminder

In simplified order, SQL executes:

  • FROM
  • WHERE
  • GROUP BY
  • HAVING
  • SELECT
  • ORDER BY

Next Step

Continue with SQL EXISTS to learn how to test for the existence of rows in a subquery.