Start learning free

LESSON 48 OF 173 · BACKEND: SQL

Filter Groups with HAVING in Go

Practice

GROUP BY makes one group per value, and COUNT(*) counts the rows in each group. Often you want only some of the groups: the categories with many products, or the cities with many customers. That needs a filter on the groups.

WHERE can't do it. It checks single rows, before any group is made, so there is no count to test yet: COUNT(*) inside WHERE is an error. HAVING is the filter for groups. It comes after GROUP BY and can test each group's count. For example, the cities with at least two customers:

var query = "SELECT city, COUNT(*) " +
	"FROM customers " +
	"GROUP BY city " +
	"HAVING COUNT(*) >= 2 "

A short rule: WHERE filters rows, HAVING filters groups. One query can use both, with WHERE before GROUP BY and HAVING after it.

Your query must print the categories that have more than two products, with their count:

category | COUNT(*)
office | 3
(1 row)

Your task: the starting code already connects db to shop.db. Below it, declare query with one string piece per clause, joined with +: select category and COUNT(*) from products, group by category, and keep only the groups whose count is more than 2.


Assignment
Follow the Coding Tutorial to write the query one clause at a time, from SELECT to HAVING.


Hint
End every string piece with a space inside the quotes, so the pieces join into one query, and every piece but the last with +. HAVING goes after GROUP BY. home and kitchen have exactly 2 products each, so use >, not >=.


STEP 1 OF 4
    Ctrl + Enter to check

    Sql Having in Go

    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free