SQL numeric literals
How the engines type bare literals like 0.1, 1.5e0 and 42: exact decimal on four engines, IEEE REAL on SQLite, and what each does with exponent notation.
- 카테고리
- Math
- Returns
numeric or REAL- In this category
- 68 of 82
구문
SELECT 0.1
SELECT 42
SELECT 1.5e0
Each block is a separate form. The support table and the examples show which engine takes which.
엔진 지원
| 엔진 | Support | 메모 |
|---|---|---|
| SQL Server | 예 | 0.1 is exact DECIMAL; 1.5e0 is FLOAT |
| PostgreSQL | 예 | 0.1 and 1.5e0 are both numeric; a float needs a cast such as 0.1::float8 or float8 '0.1' |
| MySQL | 예 | 0.1 is exact DECIMAL; 1.5e0 is DOUBLE |
| SQLite | Not built in | Every literal with a point or exponent is an IEEE REAL; there is no decimal literal type |
| Oracle | 예 | 0.1 and 1.5e0 are both NUMBER; the d or f suffix (0.1d, 0.1f) makes BINARY_DOUBLE or BINARY_FLOAT |
예시
Any engine
SELECT 0.1 + 0.2 AS literal_sum; -- 0.3; on SQLite a REAL 0.30000000000000004 printed as 0.3
SQLite
SELECT 0.1 + 0.2 = 0.3 AS eq; -- 0 (false): both sides are REAL
PostgreSQL
SELECT pg_typeof(0.1) AS a, pg_typeof(0.1e0) AS b, pg_typeof(0.1::float8) AS c; -- numeric, numeric, double precision
알아 두면 좋은 정보
- SQLite's 0.1 is a REAL, so 0.1 + 0.2 holds 0.30000000000000004 there: the shell prints 0.3, but 0.1 + 0.2 = 0.3 is false. The other four engines compute an exact 0.3.
- The exponent changes the type only on SQL Server and MySQL: 0.1 is decimal but 0.1e0 is float. PostgreSQL and Oracle keep 0.1e0 exact, so code that relies on e0 to force a float silently stays decimal there.
- Integer literals stay integers, so 7 / 2 is 3 on SQL Server, PostgreSQL and SQLite. MySQL and Oracle return 3.5 for the same expression.
Questions about numeric literals
Is the literal 0.1 exact in SQL?
On SQL Server, PostgreSQL, MySQL and Oracle yes: it is a decimal value. On SQLite no: 0.1 becomes an IEEE REAL, the nearest binary fraction, so 0.1 + 0.2 = 0.3 is false there.
How do I force a literal to be a float?
It depends on the engine. On SQL Server and MySQL, add an exponent: 0.1e0. PostgreSQL needs a cast (0.1::float8) and Oracle a suffix (0.1d). SQLite literals are already floats; there is no way to make them exact, so compute in integers instead.
Why does my literal division truncate?
Because both operands are integer literals, and SQL Server, PostgreSQL and SQLite truncate integer division: 7 / 2 is 3. Write 7 / 2.0; the point makes it a decimal literal and the division returns 3.5. MySQL and Oracle return 3.5 either way.
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, 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.