Padding zeros to the left in postgreSQL

后端 未结 3 1699
滥情空心
滥情空心 2020-12-12 23:24

I am relatively new to PostgreSQL and I know how to pad a number with zeros to the left in SQL Server but I\'m struggling to figure this out in PostgreSQL.

I have a

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-12 23:51

    The to_char() function is there to format numbers:

    select to_char(column_1, 'fm000') as column_2
    from some_table;
    

    The fm prefix ("fill mode") avoids leading spaces in the resulting varchar. The 000 simply defines the number of digits you want to have.

    psql (9.3.5)
    Type "help" for help.
    
    postgres=> with sample_numbers (nr) as (
    postgres(>     values (1),(11),(100)
    postgres(> )
    postgres-> select to_char(nr, 'fm000')
    postgres-> from sample_numbers;
     to_char
    ---------
     001
     011
     100
    (3 rows)
    
    postgres=>

    For more details on the format picture, please see the manual:
    http://www.postgresql.org/docs/current/static/functions-formatting.html

提交回复
热议问题