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

Domanda

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.

È stato utile?

Soluzione

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

Altri suggerimenti

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,'')
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top