Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

sql

postgresql

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?

like image 915
user8659376 Avatar asked Feb 23 '18 06:02

user8659376


People also ask

How do you convert boolean to text?

To convert Boolean to String in Java, use the toString() method. For this, firstly, we have declared two booleans. String str1 = new Boolean(bool1). toString(); String str2 = new Boolean(bool2).

What can boolean be converted to?

2) Boolean. toString() method converts boolean to String. The toString() is the static method of Boolean class. The signature of toString() method is given below: public static String toString(boolean b)

How do I change a boolean value in SQL?

You can update boolean value using UPDATE command. If you use the BOOLEAN data type, MySQL internally convert it into tinyint(1). It can takes true or false literal in which true indicates 1 to tinyint(1) and false indicates 0 to tinyint(1).


3 Answers

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.

like image 115
clemens Avatar answered Oct 27 '22 00:10

clemens


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;
like image 32
Raj Avatar answered Oct 27 '22 00:10

Raj


You can cast it to text like this:

CAST(table.column AS TEXT)
like image 30
Harald Nordgren Avatar answered Oct 27 '22 01:10

Harald Nordgren