Streamhub's engagement team is building a campaign targeting users who have interacted with the platform at least once.
Write a query to return the user ID and name for every user who has at least one session on record.
Assumptions:
- The
userstable contains every account on the platform. - The
sessionstable records each session;user_ididentifies the user. - The presence of any session record for a user is what qualifies them — the actual values in those session rows don't matter.
Output:
- One row per qualifying user, with columns
idandname.
Schema · analytics 5 tables
Run previews · Check grades
Write a query, then run it to see results here.
Worked solution Try it yourself first
SELECT
id,
name
FROM
users u
WHERE
EXISTS (
SELECT
1
FROM
sessions s
WHERE
s.user_id = u.id
) The shape
EXISTS tests whether the inner subquery returns at least one row for the current outer user. There's no value-membership check here. The question is presence — does any sessions row reference this user at all.
Clause by clause
SELECT id, name FROM users ureads every account on Streamhub and aliases the table asuso the inner subquery can refer back to the current row. The alias is what makes the next clause correlated.WHERE EXISTS (SELECT 1 FROM sessions s WHERE s.user_id = u.id)runs once per outer user. For eachu.id, PostgreSQL looks insidesessionsfor any row wheres.user_idmatches. The moment it finds one,EXISTSreturns true and the outer user row passes. If the lookup finds none, the test returns false and the row drops.SELECT 1is the conventional inner column becauseEXISTSdiscards the subquery's returned values entirely. The check is "did any row come back," not "what was in those rows." Returning a constant makes that indifference explicit.
Why this and not IN (SELECT user_id FROM sessions)
For this prompt, IN and EXISTS return the same users. The difference is in how the test is expressed. IN collects every user_id from sessions into a set and asks whether this user's id is in that set. EXISTS walks per outer user and short-circuits the moment a matching session shows up. The prompt also says the values in the session rows don't matter, only the presence of any row, and EXISTS reads that intent literally.
You practiced EXISTS — the membership test that cares about row presence, not row values. The convention SELECT 1 FROM ... WHERE ... reads naturally because EXISTS discards the subquery's columns regardless; returning a constant makes the indifference explicit.