AlgoMaster Logo

Exercise: GROUP BY and HAVING

Last Updated: May 12, 2026

1 min read

For this exercise, we will work with below data:

SQL

Exercise 1

Easy

From the users table, return the number of users per subscription_tier. Alias the count as user_count and order the result by subscription_tier.

SQL

Expected Query

Expected Output

Exercise 2

Easy

From the tracks table, return one row per album_id showing the number of tracks (track_count) and the total duration (total_seconds). Order by album_id.

SQL

Expected Query

Expected Output

Exercise 3

Medium

From the users table, return only the countries that have more than one user. Show country and the count as user_count, ordered by user_count descending.

SQL

Expected Query

Expected Output

Exercise 4

Medium

From the streams table, return one row per user_id showing total listening time as total_seconds for users whose total exceeds 500 seconds.

SQL

Expected Query

Expected Output

Exercise 5

Medium

From the streams table, return one row per (country, user_id) pair showing the number of streams for that combination. Restrict to rows where country IS NOT NULL and only show pairs with two or more streams. Order by country, then user_id.

SQL

Expected Query

Expected Output

Exercise 6

Hard

From the users table joined to streams, return one row per subscription_tier showing the count of distinct streaming users and total listening time. Order by total listening time descending.

SQL

Expected Query

Expected Output

Exercise 7

Hard

From the payments table, return one row per (currency, status) combination showing payment count and total amount, but only for combinations with at least 2 payments AND total amount above 20. Order by currency, then status.

SQL

Expected Query

Expected Output