Brightlane's marketing team is segmenting the customer base for a domestic campaign.
Write a query to return each customer's name, country, city, and a segment label:
'high value domestic'if the customer is US-based and has a city on record.'other'for everyone else (non-US, or US with no city, or any other combination).
Assumptions:
- The
customerstable contains every customer Brightlane has on file. - US customers are identified by
country = 'US'. - Some customers have a recorded
cityvalue; others havecityset toNULL.
Output:
- One row per customer, with columns
name,country,city, andsegment.
Schema · ecommerce 5 tables
Run previews · Check grades
Write a query, then run it to see results here.
Worked solution Try it yourself first
SELECT
name,
country,
city,
CASE
WHEN country = 'US'
AND city IS NOT NULL THEN 'high value domestic'
ELSE 'other'
END AS segment
FROM
customers The shape
A single WHEN carries both segmentation rules joined by AND. A customer has to be US-based and have a city on record for the branch to match — anything short of both gets 'other'. The compound boolean lives inside the branch the same way it would inside a WHERE.
Clause by clause
SELECT name, country, cityreturns the three input columns the marketing team needs to see alongside the segment label. The raw fields make it possible to spot-check why a row landed in'other'.CASE WHEN country = 'US' AND city IS NOT NULL THEN 'high value domestic' ELSE 'other' END AS segmentis the derived column. TheWHENis a compound boolean: both halves must be true for the branch to match.country = 'US'is the geography test;city IS NOT NULLis the data-completeness test.ANDcombines them into a single condition.IS NOT NULLis the inverse ofIS NULL— the only operator that returns a real boolean for the presence of a value. Writing it ascity <> NULLwould returnNULL(PostgreSQL three-valued logic), and the branch would never match.ELSE 'other'catches every customer who fails either half: non-US customers, US customers with no city on record, and any other combination.FROM customersis the source set: every customer on file.
Why this and not two branches
The condition could be split: one branch for country = 'US', another for city IS NOT NULL, with the same THEN label on both. That doesn't work — "either condition matches" is OR, not AND, and US customers with no city would incorrectly land in 'high value domestic'. Compound conditions belong inside one branch, joined by the right boolean operator. The single-branch form makes the rule readable as a single sentence: US and has-a-city.
You practiced building a single WHEN condition from a compound boolean. AND, OR, and IS NULL all compose inside a CASE branch the same way they do in a WHERE clause — the branch is just a boolean expression that has to evaluate to true.