Is there any technique to do in postgresql 9.3 so that it start returning 1 and 0 instead of “t” and “f” for boolean type

前端 未结 2 1598
[愿得一人]
[愿得一人] 2021-01-23 05:40

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

相关标签:
2条回答
  • 2021-01-23 05:45

    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
    
    0 讨论(0)
  • 2021-01-23 05:47

    if the column if of the boolean type then cast it to integer to compare to integer:

    select the_boolean_column::int = 1;
    

    to insert a boolean value as smallint cast it to integer fisrt

    insert into t (integer_column) values (boolean_value::int::smallint)
    

    to make the boolean_column always return integer create a view

    create view v as
    select boolean_column::int as integer_column
    from t
    

    When you query a boolean column it does not return 't' or 'f'. It returns a boolean value, true or false or null. The string representation of the value is up to the client, hence the 't'.

    0 讨论(0)
提交回复
热议问题