Start learning free

LESSON 48 OF 173 · BACKEND: SQL

Filter Groups with HAVING in TypeScript

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:

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 opens shop.db as db and starts const query: string = [ … ].join(" "). Inside the array, write one string per clause: 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
Put a comma after every string: they are the items of an array, and .join(" ") joins them into one query with a space between them. 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 TypeScript

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