user8659376
user8659376

Reputation: 399

Is it possible to convert a boolean to a string in SQL?

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

Answers (3)

Raj
Raj

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

Harald Nordgren
Harald Nordgren

Reputation: 12381

You can cast it to text like this:

CAST(table.column AS TEXT)

Upvotes: 5

clemens
clemens

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

Related Questions