30

i want to display/convert a number to character (of it's same length) using to_char() function .

In oracle i can write like

SELECT to_char(1234) FROM DUAL

But in postgres SELECT to_char(1234) is not working.

jobi88
  • 3,865
  • 8
  • 21
  • 15

4 Answers4

54

You need to supply a format mask. In PostgreSQL there is no default:

select to_char(1234, 'FM9999');

If you don't know how many digits there are, just estimate the maximum:

select to_char(1234, 'FM999999999999999999');

If the number has less digits, this won't have any side effects.

If you don't need any formatting (like decimal point, thousands separator) you can also simply cast the value to text:

select 1234::text
  • How can i find out second argument(value with the specified number of digits) for different values(of different length). – jobi88 Jan 04 '13 at 11:01
  • @jobi88: it's all documented in the manual: http://www.postgresql.org/docs/current/static/functions-formatting.html –  Jan 04 '13 at 11:02
  • 1
    I couldn't find out exact thing for me. Is there any way to get, how many 9s i need to add for to get full number. For eg in oracle i can write like. SELECT to_char(ac_no) from account. (here ac_no values may have different lengths). In this case how can i find out second argument?? – jobi88 Jan 04 '13 at 11:15
8

you have to specify a numeric format, ie:

to_char(1234, '9999')

Take a look here for more info: http://www.postgresql.org/docs/current/static/functions-formatting.html

Lorenzo L
  • 201
  • 1
  • 4
2

CAST function worked for me.

SELECT CAST(integerv AS text) AS textv
FROM (
       SELECT 1234 AS integerv
     ) x

OR

SELECT integerv::text AS textv
FROM (
       SELECT 1234 AS integerv
     ) x
changed
  • 2,103
  • 8
  • 36
  • 56
-1

You can use:

1234||''

It works on most databases.

Eduardo
  • 2,327
  • 5
  • 26
  • 43
  • I simply cannot understand why using concatenate to force an implicit type conversion is better than an explicit cast. – Merlin Feb 20 '19 at 20:24
  • 2
    @Merlin This is more compatible. So you can use the same SQL for multiple databases. – Eduardo Feb 22 '19 at 13:22