Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional CONCAT with potentially NULL or empty values

Tags:

mysql

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.

like image 803
Houdmont Avatar asked Oct 13 '11 08:10

Houdmont


People also ask

Can we use concat inside concat in SQL?

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).

How do you concatenate in MySQL?

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.


2 Answers

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) ) 
like image 127
Martin Avatar answered Sep 28 '22 11:09

Martin


Have a look at the CONCAT_WS function. It does exactly what you want.

like image 28
Mat Avatar answered Sep 28 '22 11:09

Mat