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