Home > Blockchain >  convert int to string in postgresql?
convert int to string in postgresql?

Time:10-22

I want to convert result of select statement to string:

SELECT count(*) from pg_largeobject

the result of this query will be an integer, i wanna convert it to string.

Ex: result is 12451 i want it as "12451" and its type is string .

i tried these solutions but not work:

https://www.postgresql.org/docs/9.3/functions-formatting.html

1- to_char()

to_char(SELECT count(*) from pg_largeobject, '')

but it require in second parameter the value that i dont know yet

2- cast(SELECT count(*) from pg_largeobject) as text; it gives me :

Query failed: ERROR: syntax error at or near "cast"

CodePudding user response:

You should be able to cast count(*) as text with ::text syntax:

postgres=# create extension lo;
CREATE EXTENSION
postgres=# SELECT count(*) from pg_largeobject;
 count 
-------
     0
(1 row)

postgres=# SELECT pg_typeof(count(*)) from pg_largeobject;
 pg_typeof 
-----------
 bigint
(1 row)

postgres=# SELECT pg_typeof(count(*)::text) from pg_largeobject;
 pg_typeof 
-----------
 text
(1 row)

postgres=# select version();
                                                 version                                                  
----------------------------------------------------------------------------------------------------------
 PostgreSQL 11.11 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-44), 64-bit
(1 row)

CodePudding user response:

You can use

select count(*)::TEXT from pg_catalog.pg_am;
 count 
-------
 7

CodePudding user response:

SELECT cast ( count(*)  as VARCHAR(10)) AS varchar_expression from pg_largeobject
  • Related