I am trying to cast a smallint to a boolean in PostgreSQL. This does not work out of the box, for example:
select (1::smallint)::bool;
returns "ERROR: 42846: cannot cast type smallint to boolean"
I can fix this using:
select (1::smallint)::int::bool;
but I'm wondering if there is a way I can define how to cast smallint
directly to boolean
?
The reason for this is that I (and others that I work with) have summary queries which cast an int
column from a database table to boolean
. I would like to change this column to smallint
, but doing so would brake this logic because there is no direct cast from smallint
to boolean
. Is it possible to use the postgres CREATE CAST
to define how to cast a smallint
to a boolean
?
Use the :: operator to convert strings containing numeric values to the DECIMAL data type. In our example, we converted the string ' 5800.79 ' to 5800.79 (a DECIMAL value). This operator is used to convert between different data types. It's very popular within PostgreSQL.
PostgreSQL supports a CAST operator that is used to convert a value of one type to another. Syntax: CAST ( expression AS target_type ); Let's analyze the above syntax: First, specify an expression that can be a constant, a table column, an expression that evaluates to a value.
PostgreSQL allows a type of integer type namely SMALLINT . It requires 2 bytes of storage size and can store integers in the range of -37, 767 to 32, 767. It comes in handy for storing data like the age of people, the number of pages in a book, etc. Syntax: variable_name SMALLINT.
PostgreSQL Boolean is a simple data type that we have used to represent only the structure of true or false data or values. PostgreSQL will support the SQL99 defined Boolean data type of SQL standard; Boolean is also known as “bool”, bool is an alias of Boolean data type in PostgreSQL.
I was trying:
ALTER TABLE mytable ALTER COLUMN mycol TYPE bool USING mycol::bool;
using the same approach as "Ispirer SQLWays Migrations"'s answer (cast smallint to int and then to boolean) worked:
ALTER TABLE mytable ALTER COLUMN mycol TYPE bool USING mycol::int::bool;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With