Yes / no output instead of t / f for a boolean data type in PostgreSQL

How to make a request that returns yes/noinstead of t/f(true / false)?

Current solution:

SELECT credit_card_holders.token IS NOT NULL AS premium

I found a solution to Ruby: Rails (or Ruby): Yes / No instead of True / False

But rather do it in PostgreSQL, if possible.

+4
source share
4 answers

Finished with this:

(case when credit_card_holders.token IS NOT NULL then 'Yes' else 'No' end) AS premium
+4
source

by creating custom types, you can also do this, see the following example

create table foo (id int,xid int);
insert into foo values (1,2),(2,3);

we have the following data

id xid 
-- --- 
1  2   
2  3   

and the following select statements return a boolean value.

select exists(select * from foo where xid=4);

exists
boolean
------
f

select exists(select * from foo where xid=3);

exists
boolean
------
t

ok YES NO t f, ,

create type bool2yesno as enum ('YES','NO'); --or whatever you want 'yes','no'.

boolean i.e bool2yesno

create function convert_bool_to_bool2yesno(boolean)
  returns bool2yesno
  immutable
  strict
  language sql
as $func$
  select case $1
    when false then 'NO'::bool2yesno
    when true  then 'YES'::bool2yesno
  end
$$;

cast

create cast (boolean as bool2yesno )
  with function convert_bool_to_bool2yesno(boolean)
  as assignment;

select

select exists(select * from foo where xid=4)::bool2yesno ;

exists 
bool2yesno 
----------
NO     

select exists(select * from foo where xid=3)::bool2yesno ; 
exists 
bool2yesno 
---------- 
YES 

:

CREATE CAST
CREATE FUNCTION

+3

, true/false :

SELECT (credit_card_holders.token IS NOT NULL)::text AS premium

, , t/f!

+2

humanize_boolean

true.humanize # => "Yes" false.humanize # => "No"

0

All Articles