How do I cast a string to integer and have 0 in case of error in the cast with PostgreSQL?

前端 未结 13 945
误落风尘
误落风尘 2020-12-02 06:27

In PostgreSQL I have a table with a varchar column. The data is supposed to be integers and I need it in integer type in a query. Some values are empty strings. The followin

13条回答
  •  清歌不尽
    2020-12-02 07:06

    I found the following code easy and working. Original answer is here https://www.postgresql.org/message-id/371F1510.F86C876B@sferacarta.com

    prova=> create table test(t text, i integer);
    CREATE
    
    prova=> insert into test values('123',123);
    INSERT 64579 1
    
    prova=> select cast(i as text),cast(t as int)from test;
    text|int4
    ----+----
    123| 123
    (1 row)
    

    hope it helps

提交回复
热议问题