// math reference

SQL NaN check

Detects not-a-number values. Only PostgreSQL and Oracle can store NaN at all, and both treat NaN as equal to itself, so the test is an explicit comparison or predicate.

Category
Math
Returns
boolean
In this category
60 of 82

Syntax

x = 'NaN'::float8  -- PostgreSQL
x IS NAN  -- Oracle

Each block is a separate form. The support table and the examples show which engine takes which.

Engine support

EngineSupportNotes
SQL Server Not built in No NaN values exist: operations that would produce one raise an invalid floating point operation
PostgreSQL Yes Compare directly: x = 'NaN'::float8. x <> x is always false, because PostgreSQL defines NaN = NaN as true
MySQL Not built in NaN is not storable; operations that would produce it raise an error or return NULL
SQLite Different name or syntax NaN becomes NULL on storage; check IS NULL instead
Oracle Yes IS NAN predicate: SELECT 1 FROM dual WHERE CAST('NaN' AS BINARY_DOUBLE) IS NAN

Examples

PostgreSQL

SELECT 'NaN'::float8 <> 'NaN'::float8 AS ieee_trick;  -- false: the trick does not work

Oracle

SELECT * FROM sensor_data WHERE measurement IS NAN;

PostgreSQL

SELECT COUNT(*) FROM readings WHERE value = 'NaN'::float8;  -- NaN rows

Good to know

  • IEEE says NaN is unequal to itself, which is why x <> x detects it in C or Python. PostgreSQL and Oracle deliberately break that rule so NaN can be sorted, grouped and indexed, so x <> x finds nothing there.
  • On SQLite the check is IS NULL: a NaN value never survives storage, so the NaN question becomes a NULL question.
  • Oracle's IS NAN works only on BINARY_FLOAT/BINARY_DOUBLE; NUMBER cannot hold NaN at all.

Questions about ISNAN

Does SQL have an ISNAN function?

Not by that name. Oracle has the IS NAN predicate for binary float types and PostgreSQL compares against 'NaN'::float8. SQL Server, MySQL and SQLite cannot store NaN, so there is nothing to test.

Does the x <> x trick work in SQL?

Not on the engines that store NaN. IEEE 754 makes NaN unequal to itself, but PostgreSQL and Oracle define NaN = NaN as true so it can be sorted and indexed, so x <> x is always false. Use x = 'NaN'::float8 or x IS NAN.

How do I check for NaN in SQLite?

You cannot: SQLite converts NaN to NULL on storage. Write IS NULL, and fix the producer of the NaN upstream.

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: PostgreSQL, 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.