One of my columns in the table contains 'NULL' values and I would like to replace them with certain values.
I looked at this post: Replace nulls values in sql using select statement? and followed the answer.
My sql statement:
Select ifnull(`option`, 'MCQ') as `option`
from question_table
This statement returns me the columns there are already with 'MCQ', but the 'NULL' values are not replaced yet.
Need some guidance to change this.
If you want to change the data, you need an update
:
update question_table
set option = 'MCQ'
where option is null;
A select
statement does not change the database.
If you want to update the table use Gordon's answer , but maybe you just want to return a replacement value for NULL
in the SELECT
, you can use COALESCE
:
SELECT COALESCE(`option`, 'MCQ') as `option`
FROM question_table
This selects MCQ
for every option
-value that is NULL
.
Another way is using CASE
:
SELECT CASE WHEN `option` IS NULL THEN 'MCQ' ELSE `option` END as `option`
FROM question_table
'NULL'
is a string, NULL
is a special value that means "unknown/unavailable". They are totally different things.
MySQL function IFNULL()
handles NULL
values (they cannot be compared using the regular comparison operators). You can use the regular comparison operators ( =
, <>
) to work with strings, even when they are 'NULL'
.
If your query produces 'NULL' values in the result set it means the values in the database are not NULL
but strings ( 'NULL'
).
In this case the query you need is:
SELECT IF(`option` = 'NULL', 'MCQ', `option`) AS `option`
FROM question_table
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.