Actually i am migrating my ms sql server into postgresql 9.3 and we were using int data type to store 1 and 0 for boolean values but in postgresql9.3 it is not possible. what di
By default, there is no such conversion - implicit conversion is by default used only for data types from similar groups (e.g. integer
and bigint
).
Fortunately, you can always add new implicit cast if you really need to do so.
First, we will create a new function to convert smallint
to boolean
. To do this, we will use existing C function bool_int4
.
CREATE OR REPLACE FUNCTION int2(boolean)
RETURNS smallint AS
'bool_int4'
LANGUAGE internal IMMUTABLE STRICT
COST 1;
Now we can create new implicit cast from boolean to smallint:
CREATE CAST (boolean AS smallint) WITH FUNCTION int2(boolean) as implicit;
And finally, we are ready to compare smallint and boolean directly:
select 1::smallint=true
PostgreSQL documentation warns everyone that bad things can happen when you use implicit casting unwisely:
It is wise to be conservative about marking casts as implicit. An overabundance of implicit casting paths can cause PostgreSQL to choose surprising interpretations of commands, or to be unable to resolve commands at all because there are multiple possible interpretations. A good rule of thumb is to make a cast implicitly invokable only for information-preserving transformations between types in the same general type category.
You can get list of casts for specified types from pg_catalog
, from table pg_cast:
select
castsource::regtype,
casttarget::regtype,
castcontext
from
pg_catalog.pg_cast
where
castsource::regtype in ('boolean','smallint','integer') and
casttarget::regtype in ('boolean','smallint','integer')
order by
castsource::regtype,
casttarget::regtype;
This will return (9.1.9):
castsource;casttarget;castcontext;
boolean;integer;e
smallint;integer;i
integer;boolean;e
integer;smallint;a