SQL NUMERIC vs FLOAT
Compares exact decimal types (NUMERIC, DECIMAL, NUMBER) with binary floats (FLOAT, DOUBLE, BINARY_DOUBLE): storage, speed, and the classic 0.1 + 0.2 mismatch.
- 类别
- Math
- Returns
numeric or double- In this category
- 65 of 82
语法
0.1 + 0.2 = 0.3 -- TRUE on NUMERIC, FALSE on FLOAT
引擎支持
| 引擎 | Support | 备注 |
|---|---|---|
| SQL Server | 是 | DECIMAL/NUMERIC exact; FLOAT (defaulting to 53 bits) approximate |
| PostgreSQL | 是 | numeric exact and arbitrary precision; double precision is IEEE 754 binary |
| MySQL | 是 | DECIMAL exact; DOUBLE approximate |
| SQLite | 是 | No decimal type: everything non-integer is IEEE REAL; exactness needs INTEGER cents or an extension |
| Oracle | 是 | NUMBER is exact decimal; BINARY_DOUBLE is IEEE float |
示例
PostgreSQL
SELECT 0.1::numeric + 0.2::numeric = 0.3::numeric AS exact, 0.1::float8 + 0.2::float8 = 0.3::float8 AS approx; -- true, false
MySQL
SELECT 0.1 + 0.2 = 0.3 AS dec_eq, 0.1e0 + 0.2e0 = 0.3e0 AS dbl_eq; -- 1, 0
SQL Server
SELECT price * quantity FROM order_items; -- DECIMAL math stays exact
值得了解
- The literal 0.1 is exact in a NUMERIC column but cannot exist in a float: the stored value is the nearest binary fraction, hence 0.30000000000000004.
- Floats are fixed-size and computed in hardware; NUMERIC is software arithmetic but keeps decimal values exact. Money goes in NUMERIC/DECIMAL/NUMBER.
- SQLite is the outlier: it has no decimal type, so store cents as integers or accept REAL rounding.
Questions about NUMERIC vs FLOAT
Why is 0.1 + 0.2 not 0.3 in SQL?
Because the columns are floats: binary floating point cannot represent 0.1 or 0.2 exactly, and the error compounds. In NUMERIC/DECIMAL columns the same sum is exactly 0.3.
When should I use FLOAT instead of NUMERIC?
Scientific measurements, coordinates and rates, anything where 15-17 significant digits suffice and speed matters. Anything counted in currency or units that must balance: NUMERIC.
Does SQLite have a NUMERIC type?
It has NUMERIC affinity but stores values as INTEGER or IEEE REAL: there is no true decimal storage. Keep money as integer cents in SQLite.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, 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.