Brightlane's customer success team is preparing a regional outreach list and needs every customer to have a displayable city.
Write a query to return each customer's name and a display value for their city.
Assumptions:
- The
customerstable has one row per customer with anameand acity. - Some customers have a missing
cityvalue because they registered without entering one. - A customer with a missing
cityshould appear as'Not on File'; all other customers should show their recordedcity.
Output:
- One row per customer, with columns
nameandcity.
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,
COALESCE(city, 'Not on File') AS city
FROM
customers The shape
COALESCE(city, 'Not on File') returns the recorded city for every customer who has one, and substitutes the string 'Not on File' only for the customers whose city is missing. The result is one populated value per row, which is what the outreach list needs.
Clause by clause
SELECT name, COALESCE(city, 'Not on File') AS cityreturns each customer's name alongside the substituted city value. The two arguments toCOALESCEare checked left to right: ifcityis not NULL, it wins; if it is NULL, the literal'Not on File'is returned instead. The aliasAS citykeeps the output column name matching the source.FROM customersreads the customer records. There is noWHEREbecause every customer goes into the outreach list, including the ones with a missingcity, which are exactly the rows the substitution is for.
Why this and not CASE WHEN city IS NULL THEN 'Not on File' ELSE city END
Both forms produce the same result on this data, and PostgreSQL rewrites COALESCE to that exact CASE expression internally. COALESCE(city, 'Not on File') is shorter, names the intent (first non-NULL wins), and reads as one decision rather than three clauses. Reach for CASE when the condition is more than a NULL check; for a straight NULL substitution, COALESCE is the right tool.
You practiced COALESCE(column, 'fallback') — substitute a display value when the column is missing so every output row carries something to show.