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
- value: The value you want to format (can be a date, timestamp, or number).
- format: The format string that specifies how the value should be formatted.
Commonly Used Format Patterns
For Dates and Timestamps
YYYY
: Year in 4 digits (e.g., 2024)YY
: Year in 2 digits (e.g., 24)MM
: Month number (01-12)Mon
: Abbreviated month name (e.g., Jan, Feb)Month
: Full month name (e.g., January)DD
: Day of the month (01-31)Day
: Full name of the day of the week (e.g., Sunday)HH24
: Hour in 24-hour format (00-23)HH12
: Hour in 12-hour format (01-12)MI
: Minutes (00-59)SS
: Seconds (00-59)
For Numbers
9
: Digit placeholder (can be multiple digits, e.g.,999
)0
: Digit placeholder that pads with zeros.
: Decimal point,
: Group (thousands) separatorS
: Sign (+
or “)
Examples
Formatting Dates
-
Extract Year and Month
-
Full Date with Month Name
-
Day of the Week
Formatting Numbers
-
Integer with Leading Zeros
-
Decimal Number with Thousands Separator
-
Currency Format