Re: Casting Integer to Boolean in assignment - Mailing list pgsql-general

From Ron
Subject Re: Casting Integer to Boolean in assignment
Date
Msg-id 3c598971-fa25-81f8-13d8-6e4ba0d6995b@gmail.com
Whole thread Raw
In response to Casting Integer to Boolean in assignment  (Alexandre GRAIL <postgresql.general@augure.net>)
List pgsql-general


On 1/24/19 5:04 AM, Alexandre GRAIL wrote:
Hello the list,

Maybe this question has been debated before (I didn't find anything helpful) but :

Why the default is to throw an error when casting Integer to Boolean in assignment, and accepting it everywhere else ?

So you can type :

postgres=# select 1::boolean;
 bool
------
 t
(1 row)

or

postgres=# select 0::boolean;
 bool
------
 f
(1 row)


But you *cannot* use 1 or 0 as valid input for boolean type when inserting or updating :

test=# CREATE TABLE test1 (a boolean);
CREATE TABLE
test=# INSERT INTO test1 VALUES (1);
ERROR:  column "a" is of type boolean but expression is of type integer
LINE 1: INSERT INTO test1 VALUES (1);
                                  ^
HINT:  You will need to rewrite or cast the expression.


This behavior cannot be changed, as this cast is hard coded with "Implicit?=no".

And added to this weirdness is the fact that '1' or '0' (with quote) is OK.

So is there a reason to forbid 0 and 1 as valid boolean, without explicit cast ?

I'm confused at the question.  You are happily casting 1 and 0 to boolean in the SELECT statements, and then grumbling when not casting them in the INSERT statements.  Thus, why aren't you casting during the INSERT statements?

test=# INSERT INTO test1 VALUES (1::boolean);


--
Angular momentum makes the world go 'round.

pgsql-general by date:

Previous
From: Ron
Date:
Subject: Re: [pgbackrest] Expiring the last backup?
Next
From: Stephen Frost
Date:
Subject: Re: [pgbackrest] Expiring the last backup?