Re: boolean to int - Mailing list pgsql-general

From Alex Satrapa
Subject Re: boolean to int
Date
Msg-id 40564727.4030007@lintelsys.com.au
Whole thread Raw
In response to Re: boolean to int  (Pavel Stehule <stehule@kix.fsv.cvut.cz>)
Responses Re: boolean to int
List pgsql-general
Pavel Stehule wrote:
> create or replace function int2bool (integer) returns boolean as '
>   select case when $1=1 then ''t''::boolean else ''f''::boolean end;
> ' language sql;

I'd do it slightly differently, if only to cater to the principle of least surprise:

create or replace function int2bool (integer) returns boolean as '
   select case when $1=0 then false else true end;
' language sql

That way, 0 maps to false, any non-zero value becomes true.

> create or replace function bool2int (boolean) returns integer as '
>   select case when $1 then 0 else 1 end; ' language sql;

And that's back-to-front ;)

create or replace function bool2int (boolean) returns integer as '
   select case when $1 then 1 else 0 end;
' language sql


Thanks for the example of the use of casts.

Alex Satrapa

pgsql-general by date:

Previous
From: Tom Lane
Date:
Subject: Re: Trigger loop question
Next
From: Mage
Date:
Subject: Re: boolean to int