Reputation: 399
I have a column called live_in_city
that provides a boolean value. I want to convert it to a string though.
I tried using cast((live_in_city) as varchar(256))
, but it says cannot cast type boolean to character varying.
Is there another way of doing this?
Upvotes: 12
Views: 57748
Reputation: 502
Try using below. Here you can assign value to 1 and 0 . then convert that.
Select
Cast(Case
When live_in_city=1 Then 'True'
ELse 'False' END
AS Varchar(256))
from #t
The above works if live_in_city
is a number (integer, numeric, ...).
For a real boolean
column, the following should be used:
Select Case
When live_in_city Then 'True'
ELse 'False'
END
from the_table;
Upvotes: 13
Reputation: 12381
You can cast it to text like this:
CAST(table.column AS TEXT)
Upvotes: 5
Reputation: 17721
Casting to TEXT
works fine for me in Postgres 9.5:
# select (0 = 0)::TEXT, (0 = 1)::TEXT;
text | text
------+-------
true | false
(1 row)
and also your code works as well:
# SELECT cast((1 = 1) as varchar(256)), cast((1 = 0) as varchar(256));
varchar | varchar
---------+---------
true | false
(1 row)
Note: (1 = 1)
and (1 = 0)
are placeholders for all possible expressions, that returning true
or false
.
Upvotes: 13