Search code examples
mysqlsqlconcatenationcoalesce

Using SQL concat and coalesce to display when values are null


I have the following table. city, state, and zipcode are all varchar type and can be NULL.

MyContacts
-id (int PK)
-city (varchar null)
-state (varchar null)
-zipcode (varchar null)

I would like to return city, state, and zipcode formatted as a single value as follows:

Seattle WA 98423 if all are not NULL
Seattle WA if zip is NULL
Seattle 98423 if state is NULL
WA 98423 if city is NULL
Seattle if state and zip is NULL
WA if city and zip is NULL
98423 if city and state is NULL
NULL if all of them are NULL

I have been trying something like the following, but think I am going about it wrong. Thanks

SELECT COALESCE(CONCAT(city," ",state," ",zipcode),CONCAT(city," ",states),zipcode) AS location

Solution

  • CASE WHEN COALESCE(city,state,zip_code) IS NOT NULL
    THEN
        TRIM(REPLACE(CONCAT(IFNULL(city,""),
                       " ",
                       IFNULL(state,""),
                       " ",
                       IFNULL(zip code,"")),
                "  "," "))
    ELSE
        NULL
    END
    

    OR CONCAT_WS already handles NULL effectively, so we don't need a NULL check inside it.

    CASE WHEN COALESCE(city,state,zip_code) IS NOT NULL
    THEN
        CONCAT_WS(' ',city,
                      state,
                      zipcode) 
    ELSE
        NULL
    END AS location