SQL HAVING: filtering groups, explained and practiced

HAVING keeps only the groups that meet a condition: departments with at least two people, categories with fewer than 100 units in stock, customers with two or more orders. WHERE can't do this, because it runs before the rows are grouped.

In short: ... GROUP BY department HAVING COUNT(*) >= 2 keeps only departments with at least two rows. HAVING sits right after GROUP BY and checks finished groups. WHERE checks single rows before that and knows nothing about totals or counts yet.

What you should know first: building groups with GROUP BY and filtering rows with WHERE.

Try it now

Count the employees in each department and keep only the departments where two people can cover for each other.

Task HR is planning who covers for whom during time off. Show only departments with at least two employees, with department and the number of employees.

employees 10 rows, 7 columns
employee_idfirst_namelast_namedepartmentsalaryhire_datemanager_id
1KarenMitchellManagement936002018-01-02NULL
2TomBradleySales624002019-04-011
3JuliaReyesSales468002021-06-152
4MarcusAllenSales492002020-09-012
5SarahLongWarehouse396002022-02-011
6FelixTurnerWarehouse354002024-03-185
7NinaCooperAccounting528002019-10-011
8DavidRossCustomer service384002023-05-022
9LauraHughesCustomer serviceNULL2025-09-012
10PaulWardAccounting432002022-11-147

How HAVING works

Think of a grouped query as running in this order: FROM fetches the table, WHERE drops single rows, GROUP BY builds the groups, HAVING drops whole groups, then SELECT works out the columns, ORDER BY sorts and LIMIT cuts off. So HAVING only gets its turn once COUNT, SUM and AVG are known for every group. Which categories have an average price above 100?

SELECT category,
       COUNT(*) AS products,
       ROUND(AVG(price), 2) AS avg_price
FROM products
GROUP BY category
HAVING AVG(price) > 100;
categoryproductsavg_price
Electronics3209
Furniture2319

The other four categories were calculated too, and HAVING threw them out afterwards. The HAVING condition doesn't have to appear in the SELECT list: HAVING SUM(stock) < 50 would work just as well, even though stock isn't shown at all.

WHERE or HAVING?

WHEREHAVING
checkssingle rowsfinished groups
runsbefore GROUP BYafter GROUP BY
COUNT, SUM, AVG allowednoyes, that's the usual case
exampleWHERE status = 'delivered'HAVING COUNT(*) >= 2

Rule of thumb: if the condition contains an aggregate function, it goes in HAVING. Everything else goes in WHERE. The next exercise shows that this is more than a matter of style: WHERE stock < 100 and HAVING SUM(stock) < 100 answer two different questions.

Task Purchasing is looking for categories with fewer than 100 units in stock in total. Return category and the total stock of the category, lowest total first.

products 12 rows, 5 columns
product_idnamecategorypricestock
1Copy paper, 500 sheetsPaper4.99420
2Blue ballpoint pens, 10-packWriting3.49310
3Lever arch file, grayFiling2.79185
4Comfort office chairFurniture18912
5Standing deskFurniture4495
6Black ink cartridgePrinter supplies24.964
7Yellow sticky notes, 12 padsWriting6.990
8Mono laser printer L30Electronics2198
927-inch monitorElectronics27915
10Notebook A5, ruledPaper5.49140
11Black toner XLPrinter supplies89.922
12Cross-cut shredderElectronics1290

This exercise is part of Premium.

Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.

See Premium Already Premium? Log in

The first exercise in this lesson is free.

WHERE and HAVING together

You'll often need both. WHERE decides which rows make it into the groups, HAVING then decides which groups survive. Which employees have handled at least three delivered orders?

SELECT employee_id, COUNT(*) AS delivered
FROM orders
WHERE status = 'delivered'
GROUP BY employee_id
HAVING COUNT(*) >= 3;
employee_iddelivered
35
44

Without WHERE, open and cancelled orders would be counted too. A condition without an aggregate belongs in WHERE even when it would also work in HAVING: the PostgreSQL documentation calls this more efficient, because rows that are filtered out never have to be grouped. The MySQL manual also advises against putting such conditions in HAVING.

Task Sales wants to thank repeat customers: everyone with at least two orders in status 'delivered'. Return customer_id and the number of delivered orders.

orders 18 rows, 5 columns
order_idcustomer_idorder_datestatusemployee_id
100112026-01-08delivered3
100242026-01-12delivered4
100332026-01-20delivered3
100472026-02-03delivered4
100522026-02-11cancelled8
100612026-02-25delivered3
1007102026-03-04delivered2
100852026-03-17delivered4
100982026-03-30delivered3
101062026-04-07delivered8
1011122026-04-22delivered4
101232026-05-06delivered3
101392026-05-19cancelled8
101472026-06-02shipped4
101512026-06-10shipped3
1016112026-06-12openNULL
101742026-06-13openNULL
1018102026-06-14openNULL

This exercise is part of Premium.

Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.

See Premium Already Premium? Log in

The first exercise in this lesson is free.

Aliases in HAVING

Once you've named the count with COUNT(*) AS headcount, writing HAVING headcount >= 2 is tempting. The exercise database accepts it, and so does MySQL, which documents it as an extension to the standard. PostgreSQL and SQL Server reject it, because the alias is only created in the SELECT step and HAVING is evaluated before that. So repeat the function instead: HAVING COUNT(*) >= 2 works everywhere.

Common mistakes

COUNT or SUM in WHERE

WHERE COUNT(*) >= 2 can't work, because there's nothing to count yet while a single row is being checked. The exercise tells you: "Functions like COUNT or SUM do not work in WHERE, because WHERE checks single rows. Conditions on groups go in HAVING." You get the same message if you use a count's alias in WHERE, such as WHERE headcount >= 2.

HAVING before GROUP BY, or WHERE after HAVING

... HAVING COUNT(*) >= 2 GROUP BY department gives a syntax error near "GROUP", and ... HAVING COUNT(*) >= 2 WHERE status = 'delivered' one near "WHERE". The message lists the right order: SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY, LIMIT.

Forgetting GROUP BY

SELECT department, COUNT(*) FROM employees HAVING COUNT(*) >= 2 has been allowed in SQLite since version 3.39.0: without GROUP BY, the whole table forms a single group. You get one row with 10 next to some department, and the exercise says "Your query returns only 1 row. Wanted: 4 rows."

A row condition in HAVING

HAVING COUNT(*) >= 2 AND status = 'delivered' asks for the status of a group that contains many orders with different statuses. According to its documentation, SQLite picks an arbitrary row of the group for that, while PostgreSQL rejects the query. In the exercise you get 5 rows instead of 2. The status condition belongs in WHERE.

HAVING in MySQL, PostgreSQL, SQL Server and SQLite

HAVING with aggregate functions after GROUP BY works the same everywhere. The differences:

DatabaseSELECT alias in HAVINGHAVING without GROUP BY
MySQLyes (extension)yes, all rows form one group
PostgreSQLno, write out the expressionyes, all rows form one group
SQL Serverno, HAVING is evaluated before SELECTyes, one implicit group of all rows
SQLite (these exercises)works in the exercisesyes, since version 3.39.0

Sources: MySQL Reference Manual (SELECT Statement, MySQL Handling of GROUP BY), PostgreSQL documentation (SELECT, Aggregate Functions in the tutorial), Microsoft Learn (SELECT - HAVING, SELECT statement with the logical processing order), sqlite.org (release 3.39.0, SELECT).

FAQ

Does HAVING always need an aggregate function?

Almost always. A condition on a grouping column, such as HAVING department <> 'Warehouse', is allowed, but it's better placed in WHERE. That way the warehouse rows are never grouped in the first place.

Can I combine several conditions in HAVING?

Yes, with AND and OR just like in WHERE: HAVING COUNT(*) >= 2 AND SUM(salary) > 84000 returns departments with at least two people and a salary total above 84000.

Can HAVING use a different function than the SELECT list?

Yes. You can show the count and filter on the sum, for example SELECT category, COUNT(*) ... HAVING SUM(stock) < 100.

How do I get the top three groups?

Use ORDER BY and LIMIT, not HAVING. HAVING compares each group with a fixed condition; it has no idea of rankings.

Up next: CASE WHEN

Label prices as budget or premium, sum up orders by status: CASE WHEN puts if-then logic straight into your query.

Practice CASE WHEN

Write to us

Choose language

Select your preferred language