SQL HAVING Practice: Filter Groups by COUNT

Aggregate questions such as which pages are popular need grouping and counting. HAVING lets you filter on the result of an aggregate. This exercise counts visits per page and keeps only the pages that were visited more than once.

Before you start: SELECT, GROUP BY and COUNT.

Your task

Count the visits for each page, keep only pages visited more than once and order the result with the highest count first.

Starter code

CREATE TABLE visits (page TEXT);
INSERT INTO visits VALUES ('home'), ('pricing'), ('home'), ('docs'), ('home'), ('docs');

-- Show pages visited more than once with their visit counts.

Expected result

page | total
home | 3
docs | 2

Compare column names and values rather than exact spacing.

Open this exercise

Loads the starter in the workspace. Save or export existing work first. Return here for hints and the explanation.

Need a hint?

Group by page, count the rows, then use HAVING COUNT(*) > 1. Finish with ORDER BY on the count.

Show the complete solution and walkthrough
CREATE TABLE visits (page TEXT);
INSERT INTO visits VALUES ('home'), ('pricing'), ('home'), ('docs'), ('home'), ('docs');

-- Show pages visited more than once with their visit counts.
SELECT page, COUNT(*) AS total
FROM visits
GROUP BY page
HAVING COUNT(*) > 1
ORDER BY total DESC;
  1. Select page and COUNT(*) AS total, then GROUP BY page. The groups are home with 3 rows, pricing with 1 and docs with 2.
  2. Add HAVING COUNT(*) > 1. This removes the pricing group, because its count is only 1.
  3. Order by total in descending order. The output is home with 3, followed by docs with 2.

A common mistake

A WHERE clause runs before grouping, so WHERE COUNT(*) > 1 is an error. Selecting a column that is neither grouped nor aggregated can give confusing results.

Try an edge case

If no group passes the HAVING test, the result has zero rows. Pages with equal counts need a second ORDER BY column for a stable order.

Take it one step further

Add a second ORDER BY column so that pages with equal counts are sorted alphabetically. Then change the threshold to 2 and predict the output before running.

Read the sql tool guide