Sub topic 8
Formatting and Parsing with `to_char`, `to_number`, `to_date` and `to_timestamp`
This chapter assumes that you know basic SELECT statements and PostgreSQL types such as numeric, date, and timestamp. It also assumes that you understand the difference between a value and its text representation.
A plain cast handles standard input, such as '2026-11-27'::date. Formatting functions handle a layout that you specify. They are useful when importing reports, displaying currency, or reading dates from external systems.
Formatting values with `to_char`
to_char converts a number or date/time value into text. Its second argument is a format model, which is a string of formatting instructions.
SELECT
to_char(1234.5, 'FM999,999.00') AS amount,
to_char(
timestamp '2026-11-27 21:49:54',
'YYYY-MM-DD HH24:MI:SS'
) AS created_at,
to_char(date '2026-11-27', 'DD Mon YYYY') AS short_date;The result is text:
| amount | created_at | short_date |
|---|---|---|
| 1,234.50 | 2026-11-27 21:49:54 | 27 Nov 2026 |
For numeric formats, 9 represents an optional digit and 0 represents a required digit. FM removes padding spaces. A decimal point and comma are literal formatting characters in common numeric models.
For date and timestamp formats, common patterns include:
YYYY: four-digit yearMM: two-digit monthMon: abbreviated month nameDD: day of monthHH24: hour from 00 through 23MI: minuteSS: second
Parsing text with `to_number`
to_number converts formatted text to a numeric value. The input format must describe the text layout.
SELECT to_number('1,234.50', '9,999.99') AS parsed_amount;The result is the number 1234.50, which can be used in calculations:
SELECT
to_number('1,234.50', '9,999.99') * 1.20 AS with_tax;A plain cast is often simpler for standard numeric text:
SELECT '1234.50'::numeric;Use to_number when separators, currency symbols, or a nonstandard layout must be interpreted.
Parsing dates and timestamps
to_date parses text into a date. to_timestamp parses text into a timestamp with time zone.
SELECT
to_date('27/11/2026', 'DD/MM/YYYY') AS report_date,
to_timestamp(
'27/11/2026 21:49:54',
'DD/MM/YYYY HH24:MI:SS'
) AS report_time;The format model must match the input's order. A string in MM/DD/YYYY format should not be parsed with DD/MM/YYYY, even when both values contain numbers.
Treat external text as untrusted input. A malformed value can raise an error and abort the statement. Validate or stage imported data before converting it in a large transaction.Exercise
Which function and format model parse the text 2026-11-27 08:30 as a timestamp with time zone?
Show answer
Use to_timestamp('2026-11-27 08:30', 'YYYY-MM-DD HH24:MI').