Reputation: 756
Hi this is the table I am querying:
mytable
id, name
1,name1
2,name2
3,' ' //this is a white space
4,null
but when i use this query to set blank columns to null:
update mytable set `name`= CASE `name` WHEN '' THEN NULL ELSE `name` END;
It updates even the column field which has space in it. so the result is :
1,name1
2,name2
3,null
4,null
Why does mysql treat whitespace also as '' blank? Is there any option to replace only blanks in the table to null and let the whitespaces be whitespaces?
Upvotes: 2
Views: 1430
Reputation: 39497
Because MySQL treats ''
, ' '
or even ' '
as the same.
Try querying:
select '' = ' '
It will return 1 that means true. So, MySQL treats all the whitespace strings of any length as equals.
If you want to update the rows with 0 length empty string, use Length
function:
UPDATE mytable
SET
`name` = NULL
WHERE
`name` = '' AND LENGTH(`name`) = 0;
Upvotes: 3
Reputation: 118
nullif( trim(name) , '') is NULL
https://dev.mysql.com/doc/refman/5.7/en/control-flow-functions.html#function_nullif
try this..:)
Upvotes: 2