HAVING
Introduction
HAVING keeps or drops whole groups after GROUP BY has formed them and worked out their aggregates. WHERE keeps or drops single rows before any grouping.
Here you will:
- filter groups by
COUNT,SUM,AVG,MINandMAX - see where
WHEREandHAVINGeach act, and use both in one query - combine conditions with
AND,ORandBETWEEN - see what SQLite and PostgreSQL do with the common mistakes
Why Do We Need HAVING?
Say you want the states with more than 1000 customers. The count does not exist until the rows are grouped.
The Problem
SELECT customer_state, COUNT(*) AS customer_count
FROM olist_customers_dataset
WHERE COUNT(*) > 1000
GROUP BY customer_state;The site answers misuse of aggregate: COUNT(): WHERE looks at one row at a time, and a row has no COUNT. PostgreSQL says aggregate functions are not allowed in WHERE.
The Solution
SELECT customer_state, COUNT(*) AS customer_count
FROM olist_customers_dataset
GROUP BY customer_state
HAVING COUNT(*) > 1000
ORDER BY customer_count DESC;12 of the 27 states have more than 1000 customers.
Where Each Step Acts
FROMtakes the tableWHEREkeeps the rows its condition is true forGROUP BYputs the rows that are left into groupsHAVINGkeeps the groups its condition is true forSELECTworks out each group's columnsORDER BYsorts what is left
Here are all of them in one query: the delivered orders of each state, for the states with more than 1000 of them.
SELECT c.customer_state, COUNT(*) AS delivered_orders
FROM olist_orders_dataset AS o
JOIN olist_customers_dataset AS c ON o.customer_id = c.customer_id
WHERE o.order_status = 'delivered'
GROUP BY c.customer_state
HAVING COUNT(*) > 1000
ORDER BY delivered_orders DESC;WHERE keeps 96,478 of the 99,441 orders, GROUP BY makes 27 groups of them, and HAVING keeps 12.

Watch HAVING Test the Groups
Pick a table and a GROUP BY with its HAVING, then read the rows into their groups one at a time or all at once. Once every row is in, HAVING tests each group's box in turn: its lamp shows TRUE, FALSE or NULL, a TRUE group stays in the result, and the others leave it.

Basic HAVING Syntax
HAVING comes after GROUP BY, and its condition can use aggregate functions.
Syntax
SELECT column, AGGREGATE_FUNCTION(column)
FROM table_name
GROUP BY column
HAVING aggregate_condition;
Example: Minimum Count
SELECT customer_state, COUNT(*) AS customer_count
FROM olist_customers_dataset
GROUP BY customer_state
HAVING COUNT(*) >= 1000
ORDER BY customer_count DESC;>= keeps a state with exactly 1000 too; there is none here, so the 12 rows are the same as with >.
Example: Minimum Sum
SELECT payment_type, SUM(payment_value) AS total_value
FROM olist_order_payments_dataset
GROUP BY payment_type
HAVING SUM(payment_value) > 1000000
ORDER BY total_value DESC;Two payment types took in more than 1,000,000: credit_card and boleto.
WHERE vs HAVING
WHERE and HAVING both filter; they act at different steps.
Comparison Table
| Aspect | WHERE | HAVING |
|---|---|---|
| Filters | Single rows | Groups |
| When | Before grouping | After grouping |
| Can use | Column values | Aggregate functions, and the columns it groups by |
| Needs GROUP BY | No | No: without it the whole result is one group |
SQLite allows the last row since version 3.39.0: "The HAVING clause of a SELECT statement is now allowed on any aggregate query, even queries that do not have a GROUP BY clause."
SELECT COUNT(*) AS customers
FROM olist_customers_dataset
HAVING COUNT(*) > 1000;One group, all 99,441 customers, and it passes. PostgreSQL runs the same query.
Example Comparison
WHERE filters single rows, here the customers of one city:
SELECT customer_state, COUNT(*) AS customer_count
FROM olist_customers_dataset
WHERE customer_city = 'sao paulo'
GROUP BY customer_state;HAVING filters groups, here the states with many customers:
SELECT customer_state, COUNT(*) AS cnt
FROM olist_customers_dataset
GROUP BY customer_state
HAVING COUNT(*) > 1000
ORDER BY cnt DESC;Who Placed More Than One Order?
Each order in this dataset has a customer_id of its own, so grouped by it no group has more than one order:
SELECT customer_id, COUNT(*) AS order_count
FROM olist_orders_dataset
GROUP BY customer_id
HAVING COUNT(*) > 1;The person is customer_unique_id:
SELECT c.customer_unique_id, COUNT(*) AS order_count
FROM olist_orders_dataset AS o
JOIN olist_customers_dataset AS c ON o.customer_id = c.customer_id
GROUP BY c.customer_unique_id
HAVING COUNT(*) > 1
ORDER BY order_count DESC
LIMIT 5;2,997 people placed more than one order; the busiest placed 17.
HAVING with Different Aggregates
HAVING works with any aggregate function.
HAVING with COUNT
SELECT customer_state, customer_city, COUNT(*) AS customer_count
FROM olist_customers_dataset
GROUP BY customer_state, customer_city
HAVING COUNT(*) > 100
ORDER BY customer_count DESC;138 places have more than 100 customers. They are grouped by state and city together: 163 city names stand in two or more states, and grouped by the name alone those would count as one place.
HAVING with SUM
SELECT seller_id, SUM(price) AS total_sales
FROM olist_order_items_dataset
GROUP BY seller_id
HAVING SUM(price) > 10000
ORDER BY total_sales DESC;292 of the 3,095 sellers sold more than 10000 in all; the top one 229472.63.
HAVING with AVG
SELECT seller_id, AVG(price) AS avg_price, COUNT(*) AS items_sold
FROM olist_order_items_dataset
GROUP BY seller_id
HAVING AVG(price) > 200
ORDER BY avg_price DESC;631 sellers average more than 200 an item; the first rows are sellers of a single expensive item.
HAVING with MIN and MAX
SELECT seller_id, MIN(price) AS cheapest_item, MAX(price) AS most_expensive
FROM olist_order_items_dataset
GROUP BY seller_id
HAVING MIN(price) > 100
ORDER BY cheapest_item DESC;728 sellers never sold an item for 100 or less.
Multiple HAVING Conditions
AND and OR combine conditions in HAVING as they do in WHERE.
Example: Two Conditions with AND
SELECT seller_id, COUNT(*) AS items_sold, AVG(price) AS avg_price
FROM olist_order_items_dataset
GROUP BY seller_id
HAVING COUNT(*) > 50
AND AVG(price) > 100
ORDER BY items_sold DESC;203 sellers pass both.
Example: Either Condition with OR
SELECT seller_id, COUNT(*) AS items_sold, AVG(price) AS avg_price
FROM olist_order_items_dataset
GROUP BY seller_id
HAVING COUNT(*) > 500
OR AVG(price) > 500
ORDER BY items_sold DESC;216 sellers pass at least one.
Example: A Range
SELECT customer_state, COUNT(*) AS customer_count
FROM olist_customers_dataset
GROUP BY customer_state
HAVING COUNT(*) BETWEEN 1000 AND 5000
ORDER BY customer_count DESC;7 states have from 1000 to 5000 customers.
Combining WHERE and HAVING
One query can use both: WHERE first, on the rows, then HAVING, on the groups.
Syntax
SELECT columns
FROM table_name
WHERE row_condition
GROUP BY column
HAVING group_condition
ORDER BY column;
Example: Both WHERE and HAVING
SELECT customer_state, COUNT(*) AS customer_count
FROM olist_customers_dataset
WHERE customer_city LIKE 's%'
GROUP BY customer_state
HAVING COUNT(*) >= 500
ORDER BY customer_count DESC;WHERE keeps the customers of cities whose name starts with s; HAVING keeps the states with at least 500 of them: 5 states, SP first with 21,965.
Practical Example
SELECT i.seller_id,
COUNT(*) AS items_sold,
SUM(i.price) AS total_revenue
FROM olist_order_items_dataset AS i
JOIN olist_orders_dataset AS o ON i.order_id = o.order_id
WHERE o.order_status = 'delivered'
GROUP BY i.seller_id
HAVING COUNT(*) > 50
ORDER BY total_revenue DESC
LIMIT 10;The Steps
- FROM and JOIN: each item with its order
- WHERE: the items of delivered orders
- GROUP BY: one group a seller
- HAVING: the sellers with more than 50 such items
- SELECT: each seller's count and revenue
- ORDER BY: the highest revenue first
- LIMIT: the first 10
Common Mistakes
Mistake 1: An Aggregate in WHERE
As above, WHERE COUNT(*) > 1000 fails on both engines; the count belongs in HAVING.
Mistake 2: A Column Neither Grouped Nor Aggregated in HAVING
SELECT customer_state, COUNT(*) AS customer_count
FROM olist_customers_dataset
GROUP BY customer_state
HAVING customer_city = 'sao paulo';PostgreSQL refuses it: its error says that customer_city must appear in the GROUP BY clause or be used in an aggregate function. SQLite runs it, and the site shows no rows at all, though 15,540 rows of SP are in sao paulo. Each group's test read the city of one row of that group: "If a HAVING clause is a non-aggregate expression, it is evaluated with respect to an arbitrarily selected row from the group." A condition on single rows belongs in WHERE, as in the comparison above.
Mistake 3: An Alias in HAVING
SELECT customer_state, COUNT(*) AS cnt
FROM olist_customers_dataset
GROUP BY customer_state
HAVING cnt > 1000
ORDER BY cnt DESC;The site runs it and gives the same 12 rows as HAVING COUNT(*) > 1000; SQLite has allowed it since version 2.2.4: "The label to the right of an AS in the column list of a SELECT can now be used as part of an expression in the WHERE, ORDER BY, GROUP BY, and/or HAVING clauses." PostgreSQL refuses it: column "cnt" does not exist. Repeating the aggregate works on both.
Practice
Each exercise runs on the course's tables: press Run to see its rows.
Exercise 1: Basic HAVING
Find the states with more than 1000 customers:
-- States with more than 1000 customers
SELECT
customer_state,
COUNT(*) AS customer_count
FROM olist_customers_dataset
GROUP BY customer_state
HAVING COUNT(*) > 1000
ORDER BY customer_count DESC;12 states, from SP.
Exercise 2: HAVING with SUM
Find the payment types with a total value over 5,000,000:
-- Payment types with a high total value
SELECT
payment_type,
COUNT(*) AS payment_count,
SUM(payment_value) AS total_value
FROM olist_order_payments_dataset
GROUP BY payment_type
HAVING SUM(payment_value) > 5000000
ORDER BY total_value DESC;Only credit_card, with 12542084.19.
Exercise 3: HAVING with AVG
Find the sellers whose average price is above 150:
-- Sellers with a high average price
SELECT
seller_id,
COUNT(*) AS items_sold,
AVG(price) AS avg_price
FROM olist_order_items_dataset
GROUP BY seller_id
HAVING AVG(price) > 150
ORDER BY avg_price DESC
LIMIT 10;The first is a seller of one item at 6729.
Exercise 4: Multiple HAVING Conditions
Find the sellers with at least 20 items and an average price over 100:
-- Sellers with many items and a high average price
SELECT
seller_id,
COUNT(*) AS items_sold,
AVG(price) AS avg_price,
SUM(price) AS total_revenue
FROM olist_order_items_dataset
GROUP BY seller_id
HAVING COUNT(*) >= 20
AND AVG(price) > 100
ORDER BY total_revenue DESC
LIMIT 10;The first sold 1,156 items for 229472.63.
Exercise 5: WHERE and HAVING Together
Find the review scores with at least 1000 reviews that have a comment:
-- Review scores with many commented reviews
SELECT
review_score,
COUNT(*) AS review_count
FROM olist_order_reviews_dataset
WHERE review_comment_message IS NOT NULL
GROUP BY review_score
HAVING COUNT(*) >= 1000
ORDER BY review_score DESC;5 scores pass; score 5 has 20,648 commented reviews.
Decision Guide: WHERE vs HAVING
Use WHERE When
- the condition is on a column's value in each row
- it should act before the rows are grouped
WHERE order_status = 'delivered'
WHERE price > 100
WHERE customer_city LIKE 'sao%'
Use HAVING When
- the condition is on an aggregate of each group
- it should act after the rows are grouped
HAVING COUNT(*) > 10
HAVING SUM(price) > 1000
HAVING AVG(review_score) >= 4
A condition that uses COUNT, SUM, AVG, MIN or MAX goes in HAVING; one on a row's own values goes in WHERE, where it also spares GROUP BY the rows it drops.
Summary
Key Takeaways
HAVINGfilters groups after they are formed and their aggregates worked outWHEREfilters rows before any grouping, and cannot use aggregatesHAVINGworks withCOUNT,SUM,AVG,MINandMAX, and withAND,ORandBETWEEN- One query can use
WHEREandHAVINGtogether - Without
GROUP BY,HAVINGtreats the whole result as one group - A bare column in
HAVINGis refused by PostgreSQL and read from one arbitrary row by SQLite
Comparison Summary
| Feature | WHERE | HAVING |
|---|---|---|
| Filters | Rows | Groups |
| Timing | Before GROUP BY | After GROUP BY |
| Uses aggregates | No | Yes |
| Needs GROUP BY | No | No |
Quick Reference
-- Basic HAVING
SELECT column, COUNT(*)
FROM table_name
GROUP BY column
HAVING COUNT(*) > 10;
-- WHERE and HAVING together
SELECT column, SUM(val)
FROM table_name
WHERE status = 'active'
GROUP BY column
HAVING SUM(val) > 1000;
-- Several HAVING conditions
HAVING COUNT(*) > 10 AND AVG(price) > 50
What's Next?
DISTINCT removes repeated rows from a result.