AlgoMaster Logo

Exercise: UNION and UNION ALL

Last Updated: May 12, 2026

1 min read

For this exercise, we will work with below data:

SQL

Exercise 1

Easy

Using UNION ALL, write a query that builds a unified follow feed combining follows and artist_follows. Show user_id (the follower), follow_type ('user' or 'artist'), target_id, and followed_at. Order by followed_at descending.

SQL

Expected Query

Expected Output

Exercise 2

Easy

Using UNION ALL, return all country values from users and artists together. Include rows even if the same country appears in both tables. Show country ordered alphabetically with NULLs last.

SQL

Expected Query

Expected Output

Exercise 3

Medium

Using UNION ALL, build a combined event timeline for alice_m (user_id = 1). For payments use 'payment' as event_type and the amount column; for streams use 'stream' and NULL for amount. Show event_typeevent_date, and amount. Order by event_date, then event_type.

SQL

Expected Query

Expected Output

Exercise 4

Medium

Using UNION ALL, write a query that returns the 5 most recent platform activities, where an activity is either a stream ('stream'), a user follow ('user_follow'), or an artist follow ('artist_follow'). Show usernameactivity_type, and activity_time. Order by activity_time descending and limit to 5 rows.

SQL

Expected Query

Expected Output

Exercise 5

Hard

Using UNION ALL, write a query that returns each user's total revenue contribution and total stream count side by side. For each user, sum amount for completed payments and count their streams. Show user_idtotal_paid, and total_streams. Include only users who appear in users and have at least one event in either source. Order by user_id.

SQL

Expected Query

Expected Output