Streamhub's growth team is standardizing plan display labels for the admin console. The internal plan name 'free' should not appear in the user interface.
Write a query to return each user's name and their display plan label.
Assumptions:
- The
userstable has one row per user with anameand aplan. - Users on the free plan have
plan = 'free'. - A user with
plan = 'free'should appear with'unclassified'as their display plan; all other users should show their recordedplan.
Output:
- One row per user, with columns
nameanddisplay_plan.
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
name,
COALESCE(NULLIF(plan, 'free'), 'unclassified') AS display_plan
FROM
users The shape
COALESCE(NULLIF(plan, 'free'), 'unclassified') runs a two-step rewrite in one expression: the inner NULLIF turns the sentinel 'free' into NULL, then the outer COALESCE turns that NULL into the display label 'unclassified'. Every other plan name passes through both functions unchanged.
Clause by clause
SELECT name, COALESCE(NULLIF(plan, 'free'), 'unclassified') AS display_planreturns each user's name and their display plan label. The expression nests from the inside out:NULLIFchecks ifplanequals'free'and rewrites it to NULL when it does;COALESCEthen receives that potentially-NULL value and substitutes'unclassified'when it sees NULL. For a user on'pro',NULLIFreturns'pro'untouched andCOALESCEreturns'pro'untouched.FROM usersreads every user. Free-plan users stay in the result; they are the reason the round-trip exists.
Why this and not a plain COALESCE(plan, 'unclassified')
The plain COALESCE only fires when its first argument is NULL. Here, 'free' is a recorded string, not NULL, so a plain COALESCE would leave it in place and the admin console would still display 'free'. The work is to first convert the sentinel into NULL, which is exactly what NULLIF exists for, and only then run the NULL substitution. The two functions are directional opposites that compose cleanly when a stored sentinel needs to become a display value.
You practiced COALESCE(NULLIF(...)) — rewrite a sentinel to missing in the inner step, then rewrite that missing to a display value in the outer step, in one expression.