Redshift TO_NUMBER Function and Different Arguments

  • Post author:
  • Post last modified:January 19, 2022
  • Post category:Redshift
  • Reading time:5 mins read

There are many situations where you need to pre-process the received data in order to store it in the data warehouse. For instance, you many receive currency data with currency symbol. You have pre-process currency column to remove the dollar ($) symbol and store clean value in the database. Amazon Redshift support TO_NUMBER function, you can use it to remove unwanted characters from numeric value.

Redshift TO_NUMBER Function and Different Formats

In this article, we will check how to use TO_NUMBER type conversion function with its different format. We will also check different examples to use different format parameters in TO_NUMBER function.

Amazon Redshift TO_NUMBER Function

Amazon Redshift TO_NUMBER function converts a character string containing numeric values to a numeric.

Following is the syntax of Redshift TO_NUMBER function.

to_number(string, format);

Where, string is a string to be converted. And argument format is a format string that indicates how the character string should be parsed to create the numeric value.

Amazon Redshift TO_NUMBER Argument Details

The format that will be used to convert string to a number. It can be one of the following and you can use many combinations of these argument in your TO_NUMBER function.

ParameterExplanation
9Value without leading zeros
0Value with leading zeros
.Decimal
,Group separator
PRNegative value in angle brackets
SSign
LCurrency symbol
DDecimal
GGroup separator
MIMinus sign (for negative numbers)
PLPlus sign (for positive numbers)
SGPlus/minus sign (for positive and negative numbers)
RNRoman numerals
THOrdinal number suffix
thOrdinal number suffix
VShift digits
EEEEScientific notation

Amazon Redshift TO_NUMBER Examples

Following are the some of examples with different augments.

Redshift TO_NUMBER to remove Currency Sign

Following example converts string containing the currency symbol (dollar $) to numeric.

dev=# select to_number('$12,454.8', 'L99G999D9');
 to_number
-----------
   12454.8
(1 row)

Following example handles the negative currency value

dev=# select to_number('$-12,454.8', 'LMI99G999D9');
 to_number
-----------
  -12454.8
(1 row)

Note that, we have used ‘D’ and ‘G’ to specify the decimal and group separator. You can also use comma (,) and period (.) to specify same.

Redshift Convert String to Numeric

Following example convert string containing a numeric value to a numeric or decimal value.

dev=# select to_number('12,454.8', '99,999.9');
 to_number
-----------
   12454.8
(1 row)

Related Articles,

Hope this helps 🙂