Brightlane's address formatter combines components with CONCAT_WS. Some records have no unit number on file, so the unit value is missing for those records.
Write a query to return the result of combining '42 Main Street', a SQL NULL unit, and 'Toronto' with ', ' as the separator.
Output:
- A single row with one column,
address, containing the concatenated string. The missing unit is omitted, with no doubled separator between the surrounding components.
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
CONCAT_WS(', ', '42 Main Street', NULL, 'Toronto') AS address The shape
CONCAT_WS(', ', '42 Main Street', NULL, 'Toronto') skips the NULL unit argument entirely and joins the remaining values with one ', ' between them. The result is '42 Main Street, Toronto' with a single separator, not the doubled ', , ' a naive concatenation would produce.
Clause by clause
SELECT CONCAT_WS(', ', '42 Main Street', NULL, 'Toronto') AS addressevaluates theCONCAT_WScall and labels the resulting columnaddress. The first argument is the separator', '; the remaining three arguments are the values to combine.CONCAT_WSwalks the value list, ignores every argument that is NULL, and inserts the separator only between adjacent non-NULL values. The missing unit contributes nothing, and no separator is placed where it would have sat. There is noFROMbecause the arguments are literals.
Why this and not CONCAT('42 Main Street', ', ', NULL, ', ', 'Toronto')
CONCAT would treat the NULL unit as an empty string and still include the two separator literals on either side of it, producing '42 Main Street, , Toronto' with a doubled separator. CONCAT_WS understands that the separator is its job, not the caller's, and only inserts one between values that actually exist. Whenever the same delimiter is being placed between every pair of values and any value might be missing, CONCAT_WS is the right tool.
You practiced CONCAT_WS omitting a missing argument — the function leaves it out entirely without producing a doubled separator or a trailing delimiter.