// conversion reference

SQL CAST to DECIMAL

CAST(price AS DECIMAL(10, 2)) fixes a value at two fraction digits in exact decimal arithmetic. It rounds at the scale and fails or clips when the integer part does not fit.

类别
Conversion
Returns
decimal
In this category
14 of 39

语法

CAST(expression AS DECIMAL(precision, scale))

引擎支持

引擎Support备注
SQL Server 是 Supported under this name.
PostgreSQL 是 Supported under this name.
MySQL 是 Supported under this name.
SQLite Different name or syntax accepted but only sets NUMERIC affinity; no precision, scale or rounding
Oracle 是 Supported under this name.

示例

Any engine

SELECT CAST(price AS DECIMAL(10, 2)) AS money
FROM items;

SQL Server

SELECT CAST(a AS DECIMAL(12, 4)) / b AS ratio
FROM rates;

值得了解

  • Casting rounds to the target scale: 2.345 becomes 2.35. A float source can surprise you, because the double nearest 2.345 is slightly below it and may round to 2.34.
  • DECIMAL(p, s) leaves room for at most p - s integer digits. CAST(12345 AS DECIMAL(4,2)) is an overflow error on SQL Server, PostgreSQL and Oracle, and 99.99 with a warning on MySQL.
  • Integer division happens before the cast: CAST(a / b AS DECIMAL(10,4)) keeps the already-truncated quotient on SQL Server, PostgreSQL and SQLite. Cast an operand instead: CAST(a AS DECIMAL(12,4)) / b. MySQL's / never truncates.
  • SQLite has no fixed-point type. CAST(2.345 AS DECIMAL(10,2)) returns 2.345 unchanged; use ROUND(x, 2) when you need the scale applied.

Questions about CAST AS DECIMAL

DECIMAL or NUMERIC?

The same type. NUMERIC is the SQL-standard spelling; engines treat them as identical. Use whichever your dialect's docs lead with.

Why did my division lose the decimals?

Two integer operands divide as integers on SQL Server, PostgreSQL and SQLite, so 7 / 2 is 3. Cast one operand to DECIMAL before dividing; casting the result is too late. MySQL's 7 / 2 is already 3.5000, and DIV is its integer division.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.

// fewer lookups

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.