Replace empty names with concatenated text in MySQL

There was a drop down which had a huge list of employees. But some of them hadn't name. It was empty. But not NULL in database. 

Initial query was as follows. 
SELECT emp_id, name from employees order by name asc

But it shows empty options in select list first.

Then I tried to replace name which was NULL using IFNULL function. 

SELECT aemp_id, IFNULL(name, concat('Employee - ', emp_id)) as name from employees  where name="" order by name asc

But it was failed due to empty values for name field.

Then I checked for empty value for name field. 
            NULLIF(name, "")
It will return NULL value if it is empty. Then I used COALESCE function.It returns first NULL or NULL if there no-null values in the list. Complete query as follows.

SELECT emp_id, COALESCE(NULLIF(name, ""), concat('Employee - ', emp_id)) as name from employees where name="" order by name asc

enjoy.

Chamath Gunasekara

Comments

Popular posts from this blog

Laravel Sail on Windows issue - "cmdlet Invoke-WebRequest at command pipeline position 1"

GIT Error: The following untracked working tree files would be overwritten by merge:

How to point Magento multi websites to domains