SQL Challenger
All SQL guides

Filter rows and groups with WHERE and HAVING

Build an inventory report and see how filtering before and after GROUP BY changes the result.

Sample query

SELECT genre, COUNT(*) AS available_albums, SUM(stock) AS copies
FROM albums
WHERE stock > 0
GROUP BY genre
HAVING SUM(stock) >= 8
ORDER BY copies DESC, genre;

Use WHERE for individual albums

The shop wants genres with at least eight copies available and the number of titles customers can buy in each genre. WHERE stock > 0 removes out-of-stock albums before counting available titles. Soft Circuit is the only Electronic album and has zero stock, so the query never forms an Electronic group.

Use HAVING for the genre total

GROUP BY puts the remaining albums into one group per genre. COUNT reports how many albums are in each group, and SUM adds their stock. HAVING checks the total for each finished group. Jazz passes with ten copies across two albums, even though each Jazz album has fewer than eight copies on its own.

Check which condition removed a genre

Remove HAVING and Ambient appears with two copies. With HAVING still removed, also remove WHERE. Electronic appears as one album with zero copies. When a report surprises you, inspect the eligible rows first and the grouped totals second.

Query result

genreavailable_albumscopies
Indie212
Jazz210
Try a related challenge