The primary Oracle function to convert a string to a number is TO_NUMBER, used as TO_NUMBER('123.45'). You can also use the ANSI-standard CAST('123' AS NUMBER), but TO_NUMBER offers more control over format and error handling.
Why Convert Strings to Numbers in Oracle?
Oracle stores numbers in a binary format optimized for arithmetic and comparison. When data arrives as text—from a CSV import, a web form, or a legacy system—it is a string (VARCHAR2) even if it looks like a number. You need a numeric data type to perform calculations, sort numerically, or join on numeric keys. Converting explicitly also prevents implicit conversion pitfalls, where Oracle applies its own rules that can lead to unexpected results or performance issues.
Using TO_NUMBER: Syntax and Basic Examples
The simplest form is TO_NUMBER(char), where char is a string expression. Oracle will parse the string using the default format mask, which respects the session’s NLS settings (e.g., decimal separator).
SELECT TO_NUMBER('123') FROM dual;→ returns 123SELECT TO_NUMBER('123.45') FROM dual;→ returns 123.45 (if the decimal separator is ‘.’)SELECT TO_NUMBER('-1,234.56', '9,999.99') FROM dual;→ returns -1234.56 (using a format mask)
The second argument is an optional format model that tells Oracle exactly how to interpret the string. This is essential when the string contains characters like commas, currency symbols, or a different decimal separator.
Format Models: Handling Commas, Currency, and Locale
Format models are strings of special elements that define the expected input. Common elements include:
9– a digit (leading zeros become spaces or are ignored)0– a digit (leading zeros are significant).– decimal point (position matters),– comma (group separator)$– dollar signL– local currency symbolMI– trailing minus signS– leading sign (+ or -)EEEE– scientific notation
For example, to convert the string '$1,234.56' to a number, use TO_NUMBER('$1,234.56', '$9,999.99'). To handle European decimal commas, you could specify TO_NUMBER('1.234,56', '9G999D99') where G is the group separator and D is the decimal separator (these adapt to NLS settings).
CAST vs TO_NUMBER: Which One to Use?
CAST(expr AS NUMBER) is the ANSI SQL standard and is simpler, but it does not accept a format model. It uses the default NLS settings and is less flexible. Use CAST when you need a quick conversion with default formatting, or when writing portable SQL. Use TO_NUMBER when you need to handle specific formats, validate input, or control error behavior. In practice, TO_NUMBER is more common in Oracle applications because of its format flexibility.
Handling Conversion Errors: The DEFAULT Clause and Exceptions
If the string does not match the format, Oracle raises ORA-01722: invalid number. To avoid this, you can use the DEFAULT ... ON CONVERSION ERROR clause (available since Oracle 12c). Example:
SELECT TO_NUMBER('abc' DEFAULT 0 ON CONVERSION ERROR) FROM dual; -- returns 0
This returns the default value instead of raising an error. For more complex logic, you can catch the exception in PL/SQL using EXCEPTION WHEN OTHERS and check SQLERRM, but the default clause is cleaner for simple cases.
Common Pitfalls and Misconceptions
One common mistake is assuming TO_NUMBER will trim spaces. It does trim leading and trailing whitespace by default, but not internal spaces—TO_NUMBER('1 2') will fail. Another pitfall is relying on implicit conversion in comparisons: WHERE numeric_col = '123' may work, but if the string is not a valid number, it can cause errors or ignore indexes. Always convert explicitly.
A frequent misconception is that TO_NUMBER can convert strings with trailing letters like '123abc'—it cannot. You must strip non-numeric characters first using functions like REGEXP_REPLACE.
Performance and Index Usage
When you apply TO_NUMBER to a column in a WHERE clause, Oracle cannot use a normal index on that column because the function changes the value. For example, WHERE TO_NUMBER(varchar_col) = 100 will likely do a full table scan. To improve performance, store data as numbers from the start, or create a function-based index: CREATE INDEX idx_num ON table (TO_NUMBER(varchar_col)). Also be aware that implicit conversions can hurt performance because they disable index usage similarly.
Alternatives: Implicit Conversion and Other Functions
Oracle will implicitly convert a string to a number in many contexts, such as arithmetic operations ('10' + 5) or comparisons. However, this is not recommended because it depends on NLS settings and can produce errors or wrong results. For extracting numbers from mixed text, you might use REGEXP_SUBSTR to isolate digits and then TO_NUMBER on the result. For example, TO_NUMBER(REGEXP_SUBSTR('Order 12345', '[0-9]+')) returns 12345.
Frequently Asked Questions
How do I convert a string with commas to a number?
Use TO_NUMBER('1,234', '9,999') or simply TO_NUMBER('1,234', '9999') if you want to ignore commas. The format mask tells Oracle where commas are expected. If the string uses a different thousands separator, adjust the format accordingly.
What is the difference between TO_NUMBER and CAST?
CAST is ANSI-standard and simpler, but it does not support format models. TO_NUMBER is Oracle-specific and allows you to specify a format mask, making it more flexible for complex string formats. For simple conversions with default settings, CAST works fine.
Why does TO_NUMBER return ORA-01722?
ORA-01722 means the string is not a valid number according to the format or NLS settings. Common causes: extra characters, wrong decimal separator, or a format mask that doesn’t match. Check the string and the format model, and consider using the DEFAULT ON CONVERSION ERROR clause.
Can I convert a string with leading zeros to a number?
Yes, but the leading zeros will be lost because numbers don’t store leading zeros. For example, TO_NUMBER('007') returns 7. If you need to preserve leading zeros, keep the value as a string.
How do I handle decimal commas in European format?
Use a format mask with D for decimal and G for group separator, like TO_NUMBER('1.234,56', '9G999D99'). This respects the NLS settings. Alternatively, replace the comma with a dot and remove dots as thousands separators before conversion.
Related
- How to Update a Dictionary in Python
- Federal Bank Balance Sheet: Key Figures Explained
- Power Automate String to HTML: How to Convert & Format
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Add Page Numbers with Custom Text in Microsoft WordTo add page numbers with text in Word, insert a page-number field in a header or footer, then…
- Autofit Images in Excel Cells: A Step-by-Step GuideTo autofit an image in an Excel cell, insert it with Insert > Pictures > Place in Cell…
- How to Use Slide Master in PowerPoint for Consistent SlidesTo use Slide Master in PowerPoint, open View > Slide Master, edit the top master or one of…
- Google Sheets: How to Generate Unique IDsYes. Google Sheets can generate unique IDs with a row-based formula for simple lists, or with Google Apps…
- Extend a Page Break in Excel: Adjust Print LayoutTo extend a page break in Excel, open View > Page Break Preview, then drag the blue page…
- Excel Zoom Shortcut: Fast Ways to Change MagnificationIn Excel for Microsoft 365 on Windows, press Alt, then W, then Q to open the Zoom dialog.…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.