Postgresql 9.1.9. Updating field with a string concatenated with a field that can be null give error

StackOverflow https://stackoverflow.com/questions/23336581

I don't know if this is a bug from postgres or a misunderstand my.

When I do an update like this:

UPDATE table SET empresa = 'NOMBRE ' || city

Where city is a field from table and empresa can't be null.

If city is null I get an error from Postgres informing that 'empresa' can't be null, but the whole concatenation is not null, I set a specific string anyway.

Is this a bug from postgres (version 9.1.9 in debian wheezy with backports) ?

Thanks.

有帮助吗?

解决方案

That's not a bug, this is how SQL works. Any expression (concatenation) involving NULL returns NULL.

You can either use coalesce() to make sure that city is not null or use the concat() function which treats NULL similar to an empty string:

UPDATE table 
  SET empresa = concat('NOMBRE ', city);

其他提示

Try This:

Here 'NOMBRE ' || city is also NULL if your CITY is NULL. Because any contact with NULL result in NULL.

UPDATE table SET empresa = 'NOMBRE ' || COALESCE (city,'')
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top