How to cast varchar to boolean

烈酒焚心 提交于 2020-06-27 08:03:45

问题


I have a variable 'x' which is varchar in staging table, but it is set to boolean in target table which has 'true' and 'false' values. How can I convert varchar to boolean in postgresql?


回答1:


If the varchar column contains one of the strings (case-insensitive):

  • t, true, y, yes, on, 1
  • f, false, n, no, off, 0

you can simply cast it to boolean, e.g:

select 'true'::boolean, 'false'::boolean;

 bool | bool 
------+------
 t    | f
(1 row) 

See SQLFiddle.




回答2:


For Redshift, I had the best luck with the following:

SELECT DECODE(column_name, 
             'false', '0', 
             'true', '1'
             )::integer::boolean from table_name;

This simply maps the varchar strings to '0' or '1' which Redshift can then cast first to integers, then finally to boolean.


A big advantage to this approach is that it can be expanded to include any additional strings which you would like to be mapped. i.e:

    SELECT DECODE(column_name, 
             'false', '0', 
             'no', '0', 
             'true', '1',
             'yes', '1'
             )::integer::boolean from table_name;

You can read more about the DECODE method here.




回答3:


For old PostgreSQL versions and in Redshift casting won't work but the following does:

SELECT boolin(textout('true'::varchar)), boolin(textout('false'::varchar));

See SQLFiddle also see the discussion on the PostgreSQL list.




回答4:


If you can assume anything besides true is false, then you could use:

select
  column_name = 'true' column_name_as_bool
from
  table_name;


来源:https://stackoverflow.com/questions/37687830/how-to-cast-varchar-to-boolean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!