home..

to_char in PostgreSQL

sql

to_char in PostgreSQL

The to_char function in PostgreSQL is used to format various data types, such as dates and numbers, into a string according to a specified format. It is particularly useful when you need to display data in a human-readable format or when you need specific parts of a date or number.

Basic Syntax

to_char(value, format)

Commonly Used Format Patterns

For Dates and Timestamps

For Numbers

Examples

Formatting Dates

  1. Extract Year and Month

     SELECT to_char(order_date, 'YYYY-MM') AS year_month
     FROM orders;
    
  2. Full Date with Month Name

     SELECT to_char(order_date, 'Month DD, YYYY') AS formatted_date
     FROM orders;
    
  3. Day of the Week

     SELECT to_char(order_date, 'Day') AS day_of_week
     FROM orders;
    

Formatting Numbers

  1. Integer with Leading Zeros

     SELECT to_char(7, '000') AS formatted_number;
     -- Output: '007'
    
  2. Decimal Number with Thousands Separator

     SELECT to_char(12345.67, '9,999.99') AS formatted_number;
     -- Output: '12,345.67'
    
  3. Currency Format

     SELECT to_char(12345.67, 'L9,999.99') AS formatted_number;
     -- Output depends on locale setting, e.g., '$12,345.67'
    
© 2025 Jithendra Yenugula