Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL, IFNULL(), COALESCE() on String not replacing

My statement should replace every empty title_column with 'no name', but it doesn't:

SELECT COALESCE(main_table.title_column, 'no name') AS title
FROM main_table;

IFNULL() behaves the same way.

What am I doing wrong ?

like image 276
kiltek Avatar asked Jan 18 '12 09:01

kiltek


People also ask

Is coalesce same as Ifnull?

COALESCE is useful when you have unknown number of values that you want to check. IFNULL is useful when you select columns and know that it can be null but you want to represent it with a different value. Therefore, the two functions are vastly different.

How do you replace null values in SQL using coalesce?

You can use COALESCE() to instruct using the value of another column if the target column is NULL and if that is also null then use the third column and so on. That's all about how to replace NULL with empty String or blank in SQL SERVER. You can use ISNULL() or COALESCE() to replace NULL with blanks.

Does coalesce work on empty string?

If all the arguments are blank or empty strings then the function returns blank, making Coalesce a good way to convert empty strings to blank values.

How do you replace coalesce in SQL?

Solution – To replace the null values with another values we can use the COALESCE() function in SQL. The COALESCE() function returns the first Non-Null value in a list. This query returns 5 as this is the first Non-Null value in this list.


2 Answers

COALESCE and IFNULL substitute only NULL values, your table seem to contain empty strings:

SELECT
  COALESCE(NULLIF(main_table.title_column, ''), 'no name') AS title
FROM main_table;
like image 121
newtover Avatar answered Oct 06 '22 09:10

newtover


In MySQL a NULL string and an empty ('') string are not the same thing.

You have a few options, for consistency I use CASE...

CASE WHEN main_table.title_column = '' THEN 'no name' ELSE main_table.title_column END

Other options could be the COALESCE(NULLIF()) shown on another answer (which uses NULLIF() to turn empty strings into NULLs and then uses coalesce as you wanted to).

Or possibly just IIF() to shorten the CASE statement...

IIF(main_table.title_column = '', 'no name', main_table.title_column)
like image 38
MatBailie Avatar answered Oct 06 '22 09:10

MatBailie