In the below piece of code, I am creating an Address field by concatenating various parts of an address.
However, if for instance address2
was empty, the trailing ,
will still be concatenated into Address.
This means if all fields were empty, I end up with a result of ,,,,
.
If address1
is "House Number"
and everything else is empty, I end up with House Number,,,,
.
CONCAT( COALESCE(address1,'') , ', ' , COALESCE(address2,'') , ', ' , COALESCE(address3,'') , ', ' , COALESCE(city,'') , ', ' , COALESCE(zip, '') ) AS Address,
Is there some way of conditionally placing the commas between address parts only if the content of an address part is not empty.
Such as something along the lines of (pseudo-code) IF(address1) is NULL use '' ELSE use ','
Thank you.
SQL CONCAT examplesThe inner CONCAT function concatenates the first name with space, and the outer CONCAT function concatenates the result of the inner CONCAT function with the last name. It will be much cleaner if you use the concatenation operator in Oracle (and also PostgreSQL).
CONCAT() function in MySQL is used to concatenating the given arguments. It may have one or more arguments. If all arguments are nonbinary strings, the result is a nonbinary string. If the arguments include any binary strings, the result is a binary string.
CONCAT_WS(', ', IF(LENGTH(`address1`),`address1`,NULL), IF(LENGTH(`address2`),`address2`,NULL), IF(LENGTH(`address3`),`address3`,NULL), IF(LENGTH(`city`),`city`,NULL), IF(LENGTH(`zip`),`zip`,NULL) )
Have a look at the CONCAT_WS
function. It does exactly what you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With