Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres convert integer into text

Tags:

postgresql

I have a question. I'm using a Postgrs database, and my problem is that I need to use the ints as text. I have the following solution:

CREATE FUNCTION pg_catalog.text(integer) RETURNS text STRICT IMMUTABLE LANGUAGE SQL AS 'SELECT textin(int4out($1));';

CREATE CAST (integer AS text) WITH FUNCTION pg_catalog.text(integer) AS IMPLICIT;

COMMENT ON FUNCTION pg_catalog.text(integer) IS 'convert integer to text';

I had been reading that this solution is not correct, it can cause some problems in the future. So I had been doing a research through the internet and I saw some people only use CAST, but just to convert a specific int, i.e., https://dba.stackexchange.com/questions/82511/how-to-enable-implicit-casts-in-postgresql-9-2

like image 465
rosa.tarraga Avatar asked Apr 25 '18 15:04

rosa.tarraga


People also ask

How do I change the datatype in PostgreSQL?

First, specify the name of the table to which the column you want to change belongs in the ALTER TABLE clause. Second, give the name of column whose data type will be changed in the ALTER COLUMN clause. Third, provide the new data type for the column after the TYPE keyword.

What is :: text in PostgreSQL?

PostgreSQL supports a character data type called TEXT. This data type is used to store character of unlimited length. It is represented as text in PostgreSQL. The performance of the varchar (without n) and text are the same. Syntax: variable_name TEXT.

How do I write a cast in PostgreSQL?

A cast specifies how to perform a conversion between two data types. For example, SELECT CAST(42 AS float8); converts the integer constant 42 to type float8 by invoking a previously specified function, in this case float8(int4) .

How do I round in PostgreSQL?

How to Use ROUND() Function in PostgreSQL? To avail the functionalities of the ROUND() function, you have to follow the below syntax: ROUND(Number [ , n]); Here, in this syntax, the “Number” represents a numeric value to be rounded.


1 Answers

The danger with creating an implicit cast like that is that it destabilizes the carefully balanced type system in PostgreSQL; after that, some innocent invocations of overloaded functions will stop working because due to the cast, there are suddenly too many candidate functions to make a unique choice.

It is much better to use an explicit cast:

CAST (intcol AS text)

That is standard SQL and should work everywhere.

like image 198
Laurenz Albe Avatar answered Oct 23 '22 03:10

Laurenz Albe