SQL TO_NUMBER function
Parses text into a number using a format mask that describes currency symbols, thousand separators and the decimal point. PostgreSQL and Oracle have it; the other engines use CAST, which accepts only plain digits.
- Returns
numeric- In this category
- 4 of 39
语法
TO_NUMBER(text [, format])
引擎支持
| 引擎 | Support | 备注 |
|---|---|---|
| SQL Server | Not built in | no TO_NUMBER; CAST/TRY_CAST, or PARSE with culture |
| PostgreSQL | 是 | Supported under this name. |
| MySQL | Not built in | no TO_NUMBER; CAST(x AS DECIMAL) or x + 0 |
| SQLite | Not built in | no TO_NUMBER; CAST or numeric affinity |
| Oracle | 是 | Supported under this name. |
示例
PostgreSQL
SELECT TO_NUMBER('1,234.50', '9G999D99') AS amount; -- 1234.50
Oracle
SELECT TO_NUMBER('$1,234.50', 'L9G999D99', 'NLS_NUMERIC_CHARACTERS=''.,''') AS amount
FROM dual;
MySQL
SELECT CAST('1234.50' AS DECIMAL(10,2)) AS amount;
值得了解
- PostgreSQL's TO_NUMBER quietly ignores characters it does not recognize: TO_NUMBER('12abc', '999') is 12. Pre-validate when the input is untrusted.
- The mask uses 9s and 0s: TO_NUMBER('1,234.5', '9G999D9'). G is the group separator, D the decimal, resolved per locale settings on Oracle.
- MySQL's x + 0 coerces by reading the leading number: '42abc' + 0 is 42, with a warning. CAST('42abc' AS DECIMAL(10,2)) does the same and returns 42.00.
- PostgreSQL requires the mask: TO_NUMBER(text) with one argument does not exist. Oracle's mask is optional.
Questions about TO_NUMBER
Does TO_NUMBER error on invalid text?
Oracle does (ORA-01722); PostgreSQL does not: it stops parsing and returns the leading digits, so TO_NUMBER('12abc', '999') is 12. A plain CAST of the same text errors on both engines.
What is the equivalent of TO_NUMBER in SQL Server?
CAST or TRY_CAST to a numeric type for plain digits. For separators and currency in a given locale, PARSE or TRY_PARSE: TRY_PARSE('1.234,50' AS decimal(10,2) USING 'de-DE') is 1234.50. There is no format-mask parsing.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
- Change a column's type Dialect comparison
- Cast text to a number in SQL Server, PostgreSQL, MySQL, SQLite and Oracle Dialect comparison
- Safe cast that returns NULL instead of an error in SQL Server, PostgreSQL, MySQL, SQLite and Oracle Dialect comparison
- Cast syntax in SQL Server, PostgreSQL, MySQL, SQLite and Oracle Dialect comparison
Cheat sheets for the engines that have it: PostgreSQL, Oracle.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.