Sub topic 8
Parsing strings with TO_NUMBER
This chapter assumes you can write basic SELECT and WHERE queries, know the NUMBER and VARCHAR2 types, and have read the earlier chapters on format models and NLS settings. It covers how TO_NUMBER reads text, which format elements matter when parsing, why parsing fails, and how to keep bad data from breaking a query.
What TO_NUMBER does
TO_NUMBER converts a character string into a NUMBER. It is the reverse of TO_CHAR for numbers. The full syntax is:
TO_NUMBER(expr [, fmt [, 'nlsparam']])expris the text to read.fmtis a format model that describes the text layout.nlsparamsets the separators and currency symbol used while reading, instead of the session defaults.
If you leave out fmt, Oracle accepts a plain number such as 42, -3.5 or 1.5E3. The decimal character must be the one set in your session's NLS_NUMERIC_CHARACTERS. A string with a different decimal character raises an error. With no format and no nlsparam, the same query can work for one user and fail for another.
-- Works when the decimal character is a period, fails when it is a comma
SELECT TO_NUMBER('1234.56') AS n
FROM dual;Parsing with a format model
When you supply a format model, Oracle compares the string to the model element by element. The model describes what the text looks like. It does not describe how to display the result. These are the elements you use most for parsing:
| Element | Meaning when parsing |
|---|---|
| `9` | One digit position. Fewer digits in the text are fine. |
| `0` | One digit position. Mainly useful when formatting, accepted when parsing. |
| `,` or `G` | Group separator. `G` uses the NLS group character. |
| `.` or `D` | Decimal separator. `D` uses the NLS decimal character. |
| `$` | A leading dollar sign in the text. |
| `L` | The local currency symbol from `NLS_CURRENCY`. |
| `S` | A leading or trailing sign. |
| `MI` | A trailing minus sign for negative values. |
| `PR` | Negative values wrapped in angle brackets, such as `<100>`. |
| `EEEE` | Scientific notation. |
| `X` | Hexadecimal digits. |
The first example reads US-style text. The second reads European-style text and fixes the separators with nlsparam. Both return 1234.56.
SELECT TO_NUMBER('1,234.56', '9,999.99') AS us_style,
TO_NUMBER('1.234,56', '9G999D99', 'NLS_NUMERIC_CHARACTERS='',.''') AS eu_style
FROM dual;In the second call, the nlsparam string is NLS_NUMERIC_CHARACTERS=',.'. The first character after the equals sign is the decimal character and the second is the group character. The doubled quotes are the SQL escape for a quote inside a string literal.
Prefer G and D over a literal comma and period when the text format comes from an external system. Then the model stays the same and only the nlsparam string changes per source.
Signs, currency, and other layouts
Signs and currency symbols must appear in the model, or the string fails to parse. These calls show the common cases:
SELECT TO_NUMBER('$1,234.50', '$9,999.99') AS dollars,
TO_NUMBER('100-', '999MI') AS trailing_minus,
TO_NUMBER('<100>', '999PR') AS bracketed,
TO_NUMBER('-42', 'S99') AS signed_value,
TO_NUMBER('1.5E3', '9.9EEEE') AS scientific,
TO_NUMBER('FF', 'XX') AS from_hex
FROM dual;The results are 1234.5, -100, -100, -42, 1500 and 255.
The L element reads the currency symbol that NLS_CURRENCY defines. You can override it for one call through nlsparam by adding NLS_CURRENCY=... next to NLS_NUMERIC_CHARACTERS.
Two practical points:
- The model must be wide enough for the text. A string with more digits than the model has positions fails.
TO_NUMBER('12345', '999')raises ORA-01722. - Hidden characters cause failures. A trailing space, a tab, or a non-breaking space copied from a spreadsheet makes the text invalid. Apply
TRIMto the input first.TRIMremoves ordinary spaces only, so for other whitespace useREGEXP_REPLACE.
SELECT TO_NUMBER(TRIM(' 1,250.75 '), '9,999,999.99') AS amount
FROM dual;How Oracle decides what to do
The flow below shows what happens to a string passed to TO_NUMBER.
Understanding the errors
TO_NUMBER has one dominant error, ORA-01722 (invalid number). It has several distinct causes, and the message does not say which one applies.
| Cause | Example | Fix |
|---|---|---|
| Non-numeric text | `'abc'`, `'n/a'`, `''` is NULL instead | Validate or use `DEFAULT ... ON CONVERSION ERROR` |
| Separator mismatch | `'1.234,56'` read in a session that expects a period decimal | Use `G` and `D` with `nlsparam` |
| Symbol not in the model | `'$5'` with model `'99'` | Add `$` or `L` to the model |
| Model too narrow | `'12345'` with model `'999'` | Add more `9` positions |
| Stray whitespace | `'42 '` copied from a file | `TRIM` the input |
| Implicit conversion | `WHERE order_ref = 1001` on a VARCHAR2 column | Compare with a string literal |
An empty string is the same as NULL in Oracle, so TO_NUMBER('') returns NULL and does not raise an error. Be aware of this when you load data where "empty" means "missing".
If the format model itself is malformed, for example it contains two decimal points, Oracle raises ORA-01481 (invalid number format model). That is a code mistake and not a data problem.
Implicit conversion is the common hidden case
Many ORA-01722 errors come from code that never calls TO_NUMBER. When a VARCHAR2 column is compared to a number, Oracle converts the column to a number, row by row.
-- Fails with ORA-01722 if any row of order_ref holds a non-numeric value
SELECT * FROM orders WHERE order_ref = 1001;
-- Explicit and safe: compare as text
SELECT * FROM orders WHERE order_ref = '1001';The first query also wraps the column in a conversion, so a normal index on order_ref cannot be used. The error may show up only after new data is inserted, because the table passed all earlier tests when every value happened to be numeric. If the column is meant to hold numbers, the better long-term fix is to change the data type.
Handling bad input safely (Oracle 12.2 and later)
From Oracle 12.2 you can supply a fallback value inside the call. The syntax puts the default after the expression and before the format model:
TO_NUMBER(expr DEFAULT return_value ON CONVERSION ERROR [, fmt [, 'nlsparam']])VALIDATE_CONVERSION tests a value and returns 1 if the conversion would succeed and 0 if it would not. It never raises an error.
SELECT TO_NUMBER('abc' DEFAULT -1 ON CONVERSION ERROR) AS n,
TO_DATE('31-02-2026' DEFAULT NULL ON CONVERSION ERROR, 'DD-MM-YYYY') AS d,
VALIDATE_CONVERSION('12x' AS NUMBER) AS is_valid
FROM dual;This returns -1, NULL and 0. A practical use is cleaning a column of messy text. The query below uses inline sample data so you can run it as shown.
WITH raw_data (id, amount_text) AS (
SELECT 1, '1,250.75' FROM dual UNION ALL
SELECT 2, ' 42 ' FROM dual UNION ALL
SELECT 3, 'n/a' FROM dual UNION ALL
SELECT 4, '$9.99' FROM dual
)
SELECT id,
amount_text,
TO_NUMBER(TRIM(amount_text) DEFAULT NULL ON CONVERSION ERROR,
'9,999,999.99') AS amount,
VALIDATE_CONVERSION(TRIM(amount_text) AS NUMBER, '9,999,999.99') AS is_ok
FROM raw_data;Rows 1 and 2 convert, giving 1250.75 and 42. Row 3 gives NULL because n/a is not a number. Row 4 also gives NULL, because the model has no $. That last row shows the main risk of a default: it hides errors. A NULL can mean "missing" or "my model is wrong". Use VALIDATE_CONVERSION to list the rows that fail, so you can look at them instead of silently discarding them.
SELECT order_ref
FROM orders
WHERE VALIDATE_CONVERSION(order_ref AS NUMBER) = 0;Conversions in WHERE clauses
Applying TO_NUMBER to a column has two costs. A regular index on that column cannot be used for the predicate, and every stored value must be convertible, or the query fails.
-- The column is wrapped, so a plain index on order_ref is ignored
SELECT * FROM orders WHERE TO_NUMBER(order_ref) = 1001;
-- Convert the constant side instead, when the column is text
SELECT * FROM orders WHERE order_ref = TO_CHAR(1001);The second form leaves the column untouched. It matches only text that equals '1001' exactly, so '01001' would not match. If your data has such variants, clean it first, or create a function-based index on the exact expression you query.
Evaluation order is the other trap. Oracle does not promise that one WHERE condition runs before another. This query can still raise ORA-01722, even though the first condition appears to filter out the bad rows:
-- Not safe: the optimizer may evaluate the second condition first
SELECT *
FROM orders
WHERE order_type = 'NUMERIC'
AND TO_NUMBER(order_ref) > 1000;Make the conversion itself safe instead of relying on the order:
SELECT *
FROM orders
WHERE order_type = 'NUMERIC'
AND TO_NUMBER(order_ref DEFAULT -1 ON CONVERSION ERROR) > 1000;Exercises
Exercise
Write a query that converts the text '2.450,75' to the number 2450.75 without depending on the session's NLS settings.
Show answer
SELECT TONUMBER('2.450,75', '9G999D99', 'NLSNUMERIC_CHARACTERS='',.''') AS amount FROM dual; The model uses G and D, and nlsparam sets the comma as the decimal character and the period as the group character.
Exercise
The query SELECT TO_NUMBER('12345', '999') FROM dual raises ORA-01722. Why, and how do you fix it?
Show answer
The text has five digits but the model has only three digit positions. Widen the model, for example to '99999' or '9,999' with the grouping matching the text, such as TO_NUMBER('12345', '99999').
Exercise
A column price_text has values such as '19.99', 'N/A' and '$5.00'. Write a query that returns the numeric price, or NULL when the text is not a plain number, and a second column that flags failed rows with 0.
Show answer
SELECT TONUMBER(TRIM(pricetext) DEFAULT NULL ON CONVERSION ERROR, '9999990.00') AS price, VALIDATECONVERSION(TRIM(pricetext) AS NUMBER, '9999990.00') AS is_ok FROM prices; The values 'N/A' and '$5.00' return NULL and 0 because the model has no currency element.