SQL NaN and Infinity handling
How the engines represent IEEE not-a-number and infinity: storable values on PostgreSQL and Oracle binary types, infinity only on SQLite, neither on SQL Server or MySQL.
- Catégorie
- Math
- Returns
float / double- In this category
- 59 of 82
Syntaxe
'NaN'::float8 -- PostgreSQL
BINARY_DOUBLE_NAN, BINARY_DOUBLE_INFINITY -- Oracle
9e999 -- SQLite Inf
Each block is a separate form. The support table and the examples show which engine takes which.
Prise en charge des moteurs
| Moteur | Support | Notes |
|---|---|---|
| SQL Server | Not built in | No NaN or Infinity: float overflow raises an error, and there is no literal for either |
| PostgreSQL | Oui | float accepts 'NaN', 'Infinity', '-Infinity' as literals; NaN sorts above every other value |
| MySQL | Not built in | Neither value exists: 1e308 * 10 raises 'DOUBLE value is out of range', and there are no literals |
| SQLite | Different name or syntax | Stores IEEE inf (try 9e999), but NaN becomes NULL on storage |
| Oracle | Oui | BINARY_FLOAT/BINARY_DOUBLE support NAN and BINARY_DOUBLE_INFINITY literals with IS NAN / IS INFINITE predicates |
Exemples
PostgreSQL
SELECT 'NaN'::float8 AS nan, 'Infinity'::float8 AS inf;
Oracle
SELECT BINARY_DOUBLE_INFINITY AS inf, CAST('NaN' AS BINARY_DOUBLE) AS nan FROM dual;
SQLite
SELECT 9e999 AS inf; -- Inf; a NaN value would come back as NULL
Bon à savoir
- SQLite cannot store NaN at all: an IEEE NaN becomes NULL the moment it lands in a column, so a NaN check there is a NULL check.
- PostgreSQL sorts NaN above every non-NaN value (it lands last in ORDER BY ASC), a real gotcha for top-N queries.
- PostgreSQL treats NaN as equal to NaN, unlike IEEE, so that sorting and indexes work: 'NaN'::float8 = 'NaN'::float8 is true. Oracle does the same for BINARY_DOUBLE.
Questions about NaN / Infinity
Can SQL columns hold NaN or Infinity?
PostgreSQL float and Oracle BINARY_FLOAT/BINARY_DOUBLE can, with literals like 'NaN'::float8 and BINARY_DOUBLE_INFINITY. SQLite stores infinity but turns NaN into NULL. SQL Server and MySQL raise an overflow error instead of producing either.
Why did my NaN become NULL in SQLite?
SQLite maps IEEE NaN to NULL on storage: the value simply is not representable in its type system, so a NaN check there is really a NULL check.
How does NaN sort in PostgreSQL?
Above every other value, Infinity included: ORDER BY x DESC puts NaN rows first, so a top-10 report can be all NaN. Filter x <> 'NaN' explicitly.
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: PostgreSQL, 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.