Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting smallint to boolean in PostgreSQL

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?

like image 943
mgoldwasser Avatar asked Jul 10 '15 14:07

mgoldwasser


People also ask

How do I cast to numeric in PostgreSQL?

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.

How do I cast an expression in 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.

What is Smallint in Postgres?

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.

What is the difference between Bool and Boolean in PostgreSQL?

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.


1 Answers

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;
like image 200
mowwwalker Avatar answered Sep 19 '22 01:09

mowwwalker