How to cast varchar to boolean

Ramesh picture Ramesh · Jun 7, 2016 · Viewed 17.5k times · Source

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?

Answer

klin picture klin · Jun 7, 2016

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.