This is the multi-page printable view of this section. Click here to print.

Return to the regular view of this page.

Formatting functions

Formatting functions provide a powerful tool set for converting various data types (DATE/TIME, INTEGER, FLOATING POINT) to formatted strings and for converting from formatted strings to specific data types.

Formatting functions provide a powerful tool set for converting various data types (DATE/TIME, INTEGER, FLOATING POINT) to formatted strings and for converting from formatted strings to specific data types.

1 - Template patterns for date/time formatting

In an output template string (for TO_CHAR), certain patterns are recognized and replaced with appropriately formatted data from the value to format.

In an output template string (for TO_CHAR), certain patterns are recognized and replaced with appropriately formatted data from the value to format. Any text that is not a template pattern is copied verbatim. Similarly, in an input template string (for anything other than TO_CHAR), template patterns identify the parts of the input data string to look at and the values to find there.

Certain modifiers can be applied to any template pattern to alter its behavior, as described in Template pattern modifiers for date/time formatting.

Pattern Description
HH Hour of day (00-23)
HH12 Hour of day (01-12)
HH24 Hour of day (00-23)
MI Minute (00-59)
SS Second (00-59)
MS Millisecond (000-999)
US Microsecond (000000-999999)
SSSS Seconds past midnight (0-86399)
AM A.M. PM P.M. Meridian indicator (uppercase)
am a.m. pm p.m. Meridian indicator (lowercase)
Y YYY Year (4 and more digits) with comma
YYYY Year (4 and more digits)
YYY Last 3 digits of year
YY Last 2 digits of year
Y Last digit of year
IYYY ISO year (4 and more digits)
IYY Last 3 digits of ISO year
IY Last 2 digits of ISO year
I Last digits of ISO year
BC B.C. AD A.D. Era indicator (uppercase)
bc b.c. ad a.d. Era indicator (lowercase)
MONTH Full uppercase month name (blank-padded to 9 chars)
Month Full mixed-case month name (blank-padded to 9 chars)
month Full lowercase month name (blank-padded to 9 chars)
MON Abbreviated uppercase month name (3 chars)
Mon Abbreviated mixed-case month name (3 chars)
mon Abbreviated lowercase month name (3 chars)
MM Month number (01-12)
DAY Full uppercase day name (blank-padded to 9 chars)
Day Full mixed-case day name (blank-padded to 9 chars)
day full lowercase day name (blank-padded to 9 chars)
DY Abbreviated uppercase day name (3 chars)
Dy Abbreviated mixed-case day name (3 chars)
dy Abbreviated lowercase day name (3 chars)
DDD Day of year (001-366)
DD

Day of month (01-31) for TIMESTAMP

D Day of week (1-7; Sunday is 1)
W Week of month (1-5) (The first week starts on the first day of the month.)
WW Week number of year (1-53) (The first week starts on the first day of the year.)
IW ISO week number of year (The first Thursday of the new year is in week 1.)
CC Century (2 digits)
J Julian Day (days since January 1, 4712 BC)
Q Quarter
RM Month in Roman numerals (I-XII; I=January) (uppercase)
rm Month in Roman numerals (i-xii; i=January) (lowercase)
TZ Time-zone name (uppercase)
tz Time-zone name (lowercase)

Examples

Use TO_TIMESTAMP to convert an expression using the pattern 'YYY MON':

=> SELECT TO_TIMESTAMP('2017 JUN', 'YYYY MON');
    TO_TIMESTAMP
---------------------
 2017-06-01 00:00:00
(1 row)

Use TO_DATE to convert an expression using the pattern 'YYY-MMDD':

=> SELECT TO_DATE('2017-1231', 'YYYY-MMDD');
  TO_DATE
------------
 2017-12-31
(1 row)

1.1 - Template pattern modifiers for date/time formatting

Certain modifiers can be applied to any template pattern to alter its behavior.

Certain modifiers can be applied to any template pattern to alter its behavior. For example, FMMonth is the Month pattern with the FM modifier.

Modifier Description
AM Time is before 12:00
AT Ignored
JULIAN, JD, J Next field is Julian Day
FM prefix

Fill mode (suppress padding blanks and zeros)

For example: FMMonth

Note: The FM modifier suppresses leading zeros and trailing blanks that would otherwise be added to make the output of a pattern fixed width.

FX prefix

Fixed format global option

For example: FX Month DD Day

ON Ignored
PM Time is on or after 12:00
T Next field is time
TH suffix

Uppercase ordinal number suffix

For example: DDTH

th suffix

Lowercase ordinal number suffix

For example: DDth

TM prefix Translation mode (print localized day and month names based on lc_messages). For example: TMMonth

2 - Template patterns for numeric formatting

A sign formatted using SG, PL, or MI is not anchored to the number.
Pattern Description
9 Value with the specified number of digits
0 Value with leading zeros
. Decimal point
, Group (thousand) separator
PR Negative value in angle brackets
S Sign anchored to number (uses locale)
L Currency symbol (uses locale)
D Decimal point (uses locale)
G Group separator (uses locale)
MI Minus sign in specified position (if number < 0)
PL Plus sign in specified position (if number > 0)
SG Plus/minus sign in specified position
RN Roman numeral (input between 1 and 3999)
TH/th Ordinal number suffix
V Shift specified number of digits

Usage

  • A sign formatted using SG, PL, or MI is not anchored to the number. For example:

    => SELECT to_char(-12, 'S9999'), to_char(-12, 'MI9999');
     to_char | to_char
    ---------+---------
       -12   | -  12
    (1 row)
    
    • TO_CHAR(-12, 'S9999') produces ' -12'

    • TO_CHAR(-12, 'MI9999') produces '- 12'

  • 9 results in a value with the same number of digits as there are 9s. If a digit is not available it outputs a space.

  • TH does not convert values less than zero and does not convert fractional numbers.

  • V effectively multiplies the input values by 10^n, where n is the number of digits following V. TO_CHAR does not support the use of V combined with a decimal point—for example: 99.9V99.

3 - TO_BITSTRING

Returns a VARCHAR that represents the given VARBINARY value in bitstring format.

Returns a VARCHAR that represents the given VARBINARY value in bitstring format. This function is the inverse of BITSTRING_TO_BINARY.

Behavior type

Immutable

Syntax

TO_BITSTRING ( expression )

Arguments

expression
The VARCHAR string to process.

Examples

=> SELECT TO_BITSTRING('ab'::BINARY(2));
   to_bitstring
------------------
 0110000101100010
(1 row)

=> SELECT TO_BITSTRING(HEX_TO_BINARY('0x10'));
 to_bitstring
--------------
00010000
(1 row)

=> SELECT TO_BITSTRING(HEX_TO_BINARY('0xF0'));
 to_bitstring
--------------
11110000
(1 row)

See also

BITCOUNT

4 - TO_CHAR

Converts date/time and numeric values into text strings.

Converts date/time and numeric values into text strings.

Behavior type

Stable

Syntax

TO_CHAR ( expression [, pattern ] )

Parameters

expression
Specifies the value to convert, one of the following data types:

The following restrictions apply:

  • TO_CHAR does not support binary data types BINARY and VARBINARY

  • TO_CHAR does not support the use of V combined with a decimal point—for example, 99.9V99

pattern
A CHAR or VARCHAR that specifies an output pattern string. See:

Notes

  • Vertica pads TO_CHAR output with a leading space, so positive and negative values have the same length. To suppress padding, use the FM prefix.

  • TO_CHAR accepts TIME and TIMETZ data types as inputs if you explicitly cast TIME to TIMESTAMP and TIMETZ to TIMESTAMPTZ.

    => SELECT TO_CHAR(TIME '14:34:06.4','HH12:MI am'), TO_CHAR(TIMETZ '14:34:06.4+6','HH12:MI am');
     TO_CHAR  | TO_CHAR
    ----------+----------
     02:34 pm | 04:34 am
    (1 row)
    
  • You can extract the timezone hour from TIMETZ:

    => SELECT EXTRACT(timezone_hour FROM TIMETZ '10:30+13:30');
     date_part
    -----------
            13
    (1 row)
    
  • Ordinary text is allowed in TO_CHAR templates and is output literally. You can put a substring in double quotes to force it to be interpreted as literal text even if it contains pattern key words. In the following example, YYYY is replaced by the year data, but the Y in Year is not:

    => SELECT to_char(CURRENT_TIMESTAMP, '"Hello Year " YYYY');
         to_char
    ------------------
     Hello Year  2021
    (1 row)
    
  • TO_CHAR uses different day-of-the-week numbering (see the D template pattern) than EXTRACT.

  • Given an INTERVAL type, TO_CHAR formats HH and HH12 as hours in a single day, while HH24 can output hours exceeding a single day—for example, >24.

  • To include a double quote (") character in output, precede it with a double backslash (\\). This is necessary because the backslash already has a special meaning in a string constant. For example: '\\"YYYY Month\\"'

  • When rounding, the last digit of the rounded representation is selected to be even if the number is exactly half way between the two.

Examples

TO_CHAR expression and pattern argument Output
CURRENT_TIMESTAMP, 'Day, DD HH12:MI:SS' Tuesday , 06 05:39:18
CURRENT_TIMESTAMP, 'FMDay, FMDD HH12:MI:SS' Tuesday, 6 05:39:18
TIMETZ '14:34:06.4+6','HH12:MI am' 04:34 am
-0.1, '99.99' -.10
-0.1, 'FM9.99' -.1
0.1, '0.9' 0.1
12, '9990999.9'
`0012.0`
12, 'FM9990999.9' 0012.
485, '999' 485
-485, '999' -485
485, '9 9 9' 4 8 5
1485, '9,999' 1,485
1485, '9G999' 1 485
148.5, '999.999' 148.500
148.5, 'FM999.999' 148.5
148.5, 'FM999.990' 148.500
148.5, '999D999' 148,500
3148.5, '9G999D999' 3 148,500
-485, '999S' 485-
-485, '999MI' 485-
485, '999MI' 485
485, 'FM999MI' 485
485, 'PL999' +485
485, 'SG999' +485
-485, 'SG999' -485
-485, '9SG99' 4-85
-485, '999PR' <485>
485, 'L999' DM 485
485, 'RN'
    `CDLXXXV`
485, 'FMRN' CDLXXXV
5.2, 'FMRN' V
482, '999th' 482nd
485, '"Good number:"999' Good number: 485
485.8, '"Pre:"999" Post:" .999' Pre: 485 Post: .800
12, '99V999' 12000
12.4, '99V999' 12400
12.45, '99V9' 125
-1234.567 -1234.567
'1999-12-25'::DATE 1999-12-25
'1999-12-25 11:31'::TIMESTAMP 1999-12-25 11:31:00
'1999-12-25 11:31 EST'::TIMESTAMPTZ 1999-12-25 11:31:00-05
'3 days 1000.333 secs'::INTERVAL 3 days 00:16:40.333

See also

DATE_PART

5 - TO_DATE

Converts a string value to a DATE type.

Converts a string value to a DATE type.

Behavior type

Stable

Syntax

TO_DATE ( expression , pattern )

Parameters

expression
Specifies the string value to convert, either CHAR or VARCHAR.
pattern
A CHAR or VARCHAR that specifies an output pattern string. See:

Input value considerations

TO_DATE requires a CHAR or VARCHAR expression. For other input types, use TO_CHAR to perform an explicit cast to a CHAR or VARCHAR before using this function.

Notes

  • To use a double quote character in the output, precede it with a double backslash. This is necessary because the backslash already has a special meaning in a string constant. For example: '\\"YYYY Month\\"'
  • TO_TIMESTAMP, TO_TIMESTAMP_TZ, and TO_DATE skip multiple blank spaces in the input string if the FX option is not used. FX must be specified as the first item in the template. For example:

    • TO_TIMESTAMP('2000 JUN', 'YYYY MON') is correct.

    • TO_TIMESTAMP('2000 JUN', 'FXYYYY MON') returns an error, because TO_TIMESTAMP expects one space only.

  • The YYYY conversion from string to TIMESTAMP or DATE has a restriction if you use a year with more than four digits. You must use a non-digit character or template after YYYY, otherwise the year is always interpreted as four digits. For example, given the following arguments, TO_DATE interprets the five-digit year 20000 as a four-digit year:

    => SELECT TO_DATE('200001131','YYYYMMDD');
      TO_DATE
    ------------
     2000-01-13
    (1 row)
    

    Instead, use a non-digit separator after the year. For example:

    => SELECT TO_DATE('20000-1131', 'YYYY-MMDD');
       TO_DATE
    -------------
     20000-12-01
    (1 row)
    
  • In conversions from string to TIMESTAMP or DATE, the CC field is ignored if there is a YYY, YYYY or Y,YYY field. If CC is used with YY or Y, then the year is computed as (CC–1)*100+YY.

Examples

=> SELECT TO_DATE('13 Feb 2000', 'DD Mon YYYY');
  to_date
------------
 2000-02-13
(1 row)

See also

Date/time functions

6 - TO_HEX

Returns a VARCHAR or VARBINARY representing the hexadecimal equivalent of a number.

Returns a VARCHAR or VARBINARY representing the hexadecimal equivalent of a number. This function is the inverse of HEX_TO_BINARY.

Behavior type

Immutable

Syntax

TO_HEX ( number )

Arguments

number
An INTEGER or VARBINARY value to convert to hexadecimal. If you supply a VARBINARY argument, the function's return value is not preceded by 0x.

Examples

=> SELECT TO_HEX(123456789);
 TO_HEX
---------
 75bcd15
(1 row)

For VARBINARY inputs, the returned value is not preceded by 0x. For example:

=> SELECT TO_HEX('ab'::binary(2));
 TO_HEX
--------
 6162
(1 row)

7 - TO_NUMBER

Converts a string value to DOUBLE PRECISION.

Converts a string value to DOUBLE PRECISION.

Behavior type

Stable

Syntax

TO_NUMBER ( expression, [ pattern ] )

Parameters

expression
Specifies the string value to convert, either CHAR or VARCHAR.
pattern
A string value, either CHAR or VARCHAR, that specifies an output pattern string using one of the supported Template patterns for numeric formatting. If you omit this parameter, TO_NUMBER returns a floating point.

Notes

To use a double quote character in the output, precede it with a double backslash. This is necessary because the backslash already has a special meaning in a string constant. For example: '\\"YYYY Month\\"'

Examples

=> SELECT TO_NUMBER('MCML', 'rn');
TO_NUMBER
-----------
1950
(1 row)

It the pattern parameter is omitted, the function returns a floating point. For example:

=> SELECT TO_NUMBER('-123.456e-01');
 TO_NUMBER
-----------
  -12.3456

8 - TO_TIMESTAMP

Converts a string value or a UNIX/POSIX epoch value to a TIMESTAMP type.

Converts a string value or a UNIX/POSIX epoch value to a TIMESTAMP type.

Behavior type

Stable

Syntax

TO_TIMESTAMP ( { expression, pattern } | unix-epoch )

Parameters

expression
Specifies the string value to convert, of type CHAR or VARCHAR.
pattern
A CHAR or VARCHAR that specifies an output pattern string. See:
unix-epoch
DOUBLE PRECISION value that specifies some number of seconds elapsed since midnight UTC of January 1, 1970, excluding leap seconds. INTEGER values are implicitly cast to DOUBLE PRECISION.

Notes

  • Millisecond (MS) and microsecond (US) values in a conversion from string to TIMESTAMP are used as part of the seconds after the decimal point. For example TO_TIMESTAMP('12:3', 'SS:MS') is not 3 milliseconds, but 300, because the conversion counts it as 12 + 0.3 seconds. This means for the format SS:MS, the input values 12:3, 12:30, and 12:300 specify the same number of milliseconds. To get three milliseconds, use 12:003, which the conversion counts as 12 + 0.003 = 12.003 seconds.

    Here is a more complex example: TO_TIMESTAMP('15:12:02.020.001230', 'HH:MI:SS.MS.US') is 15 hours, 12 minutes, and 2 seconds + 20 milliseconds + 1230 microseconds = 2.021230 seconds.

  • To use a double quote character in the output, precede it with a double backslash. This is necessary because the backslash already has a special meaning in a string constant. For example: '\\"YYYY Month\\"'

  • TO_TIMESTAMP, TO_TIMESTAMP_TZ, and TO_DATE skip multiple blank spaces in the input string if the FX option is not used. FX must be specified as the first item in the template. For example:

    • TO_TIMESTAMP('2000 JUN', 'YYYY MON') is correct.

    • TO_TIMESTAMP('2000 JUN', 'FXYYYY MON') returns an error, because TO_TIMESTAMP expects one space only.

  • The YYYY conversion from string to TIMESTAMP or DATE has a restriction if you use a year with more than four digits. You must use a non-digit character or template after YYYY, otherwise the year is always interpreted as four digits. For example, given the following arguments, TO_DATE interprets the five-digit year 20000 as a four-digit year:

    => SELECT TO_DATE('200001131','YYYYMMDD');
      TO_DATE
    ------------
     2000-01-13
    (1 row)
    

    Instead, use a non-digit separator after the year. For example:

    => SELECT TO_DATE('20000-1131', 'YYYY-MMDD');
       TO_DATE
    -------------
     20000-12-01
    (1 row)
    
  • In conversions from string to TIMESTAMP or DATE, the CC field is ignored if there is a YYY, YYYY or Y,YYY field. If CC is used with YY or Y, then the year is computed as (CC–1)*100+YY.

Examples

=> SELECT TO_TIMESTAMP('13 Feb 2009', 'DD Mon YYYY');
    TO_TIMESTAMP
---------------------
 1200-02-13 00:00:00
(1 row)
=> SELECT TO_TIMESTAMP(200120400);
    TO_TIMESTAMP
---------------------
 1976-05-05 01:00:00
(1 row)

See also

Date/time functions

9 - TO_TIMESTAMP_TZ

Converts a string value or a UNIX/POSIX epoch value to a TIMESTAMP WITH TIME ZONE type.

Converts a string value or a UNIX/POSIX epoch value to a TIMESTAMP WITH TIME ZONE type.

Behavior type

Immutable if single argument form, Stable otherwise.

Syntax

TO_TIMESTAMP_TZ ( { expression, pattern } | unix-epoch )

Parameters

expression
Specifies the string value to convert, of type CHAR or VARCHAR.
pattern
A CHAR or VARCHAR that specifies an output pattern string. See:
unix-epoch
A DOUBLE PRECISION value that specifies some number of seconds elapsed since midnight UTC of January 1, 1970, excluding leap seconds. INTEGER values are implicitly cast to DOUBLE PRECISION.

Notes

  • Millisecond (MS) and microsecond (US) values in a conversion from string to TIMESTAMP are used as part of the seconds after the decimal point. For example TO_TIMESTAMP('12:3', 'SS:MS') is not 3 milliseconds, but 300, because the conversion counts it as 12 + 0.3 seconds. This means for the format SS:MS, the input values 12:3, 12:30, and 12:300 specify the same number of milliseconds. To get three milliseconds, use 12:003, which the conversion counts as 12 + 0.003 = 12.003 seconds.

    Here is a more complex example: TO_TIMESTAMP('15:12:02.020.001230', 'HH:MI:SS.MS.US') is 15 hours, 12 minutes, and 2 seconds + 20 milliseconds + 1230 microseconds = 2.021230 seconds.

  • To use a double quote character in the output, precede it with a double backslash. This is necessary because the backslash already has a special meaning in a string constant. For example: '\\"YYYY Month\\"'

  • TO_TIMESTAMP, TO_TIMESTAMP_TZ, and TO_DATE skip multiple blank spaces in the input string if the FX option is not used. FX must be specified as the first item in the template. For example:

    • TO_TIMESTAMP('2000 JUN', 'YYYY MON') is correct.

    • TO_TIMESTAMP('2000 JUN', 'FXYYYY MON') returns an error, because TO_TIMESTAMP expects one space only.

  • The YYYY conversion from string to TIMESTAMP or DATE has a restriction if you use a year with more than four digits. You must use a non-digit character or template after YYYY, otherwise the year is always interpreted as four digits. For example, given the following arguments, TO_DATE interprets the five-digit year 20000 as a four-digit year:

    => SELECT TO_DATE('200001131','YYYYMMDD');
      TO_DATE
    ------------
     2000-01-13
    (1 row)
    

    Instead, use a non-digit separator after the year. For example:

    => SELECT TO_DATE('20000-1131', 'YYYY-MMDD');
       TO_DATE
    -------------
     20000-12-01
    (1 row)
    
  • In conversions from string to TIMESTAMP or DATE, the CC field is ignored if there is a YYY, YYYY or Y,YYY field. If CC is used with YY or Y, then the year is computed as (CC–1)*100+YY.

Examples

=> SELECT TO_TIMESTAMP_TZ('13 Feb 2009', 'DD Mon YYY');
    TO_TIMESTAMP_TZ
------------------------
 1200-02-13 00:00:00-05
(1 row)

=> SELECT TO_TIMESTAMP_TZ(200120400);
    TO_TIMESTAMP_TZ
------------------------
 1976-05-05 01:00:00-04
(1 row)

See also

Date/time functions