Cast string to number, interpreting null or empty string as 0

后端 未结 4 1073
情话喂你
情话喂你 2021-02-05 00:31

I have a Postgres table with a string column carrying numeric values. I need to convert these strings to numbers for math, but I need both NULL values as well as em

4条回答
  •  不思量自难忘°
    2021-02-05 00:44

    Actually, you can cast NULL to int, you just can't cast an empty string to int. Assuming you want NULL in the new column if data1 contains an empty string or NULL, you can do something like this:

    UPDATE table SET data2 = cast(nullif(data1, '') AS int);
    

    or

    UPDATE table SET data2 = nullif(data1, '')::int;
    

    Reference

提交回复
热议问题