-1

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.

7
  • 3
    Check your data, is the option value really NULL or 'NULL'? Commented Jun 16, 2015 at 14:13
  • Are you filtering out data with some where condition ? This should return the null values as 'MCQ'. Commented Jun 16, 2015 at 14:13
  • I am not filtering out data. If i use the search functionality and put "IS NULL", I am able to get all the data out that have option as NULL. Commented Jun 16, 2015 at 14:15
  • @lakesh . . . How do you know whether the values are changing or not? Is that the entire query? Can you edit your question and provide sample data and the results you are getting with your query? Commented Jun 16, 2015 at 14:15
  • I click the database again and search if there is any NULL options. It shows it to me. Commented Jun 16, 2015 at 14:16

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

3 Comments

tried this as well. it just returned me the column of options with 'MCQ'
I wanted it to replace it.
@lakesh: if you want to update your table use UPDATE... of course.
0

'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 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.