// math reference

SQL NANVL function

Returns the second argument when the first is NaN, otherwise the first: NANVL(measurement, 0) turns NaN readings into zero.

Category
Math
Returns
same type as the input
In this category
61 of 82

Syntax

NANVL(n, default)

Engine support

EngineSupportNotes
SQL Server Yes No NaN representation, so no NANVL; ISNULL covers missing values
PostgreSQL Not built in No NANVL; CASE WHEN x = 'NaN'::float8 THEN default ELSE x END
MySQL Not built in No NANVL and no storable NaN; COALESCE covers NULL
SQLite Not built in No NANVL; NaN never survives storage; COALESCE(x, default) covers the NULL it becomes
Oracle Not built in NANVL(n, default) is built in for BINARY_FLOAT/BINARY_DOUBLE input

Examples

Oracle

SELECT NANVL(CAST('NaN' AS BINARY_DOUBLE), 0) AS cleaned FROM dual;  -- 0

Oracle

SELECT NANVL(measurement, -1) AS flag_bad
FROM sensor_data;

Good to know

  • NANVL only fires on NaN: NULL passes through untouched, so combine with NVL/COALESCE when both are possible: NVL(NANVL(x, 0), 0).
  • It exists because Oracle's binary float types can hold NaN from computations such as POWER(-8d, 1/3) or 0d / 0d; NUMBER columns cannot, so NANVL is pointless there.
  • Elsewhere the emulation is a CASE: PostgreSQL CASE WHEN x = 'NaN'::float8 THEN d ELSE x END; SQLite COALESCE(x, d) after the NaN-to-NULL conversion.

Questions about NANVL

What is the PostgreSQL equivalent of NANVL?

A CASE: CASE WHEN x = 'NaN'::float8 THEN 0 ELSE x END. PostgreSQL has no NANVL function, but its float can hold NaN so the comparison works.

Does NANVL also replace NULL?

No. NULL passes through. Chain NVL(NANVL(x, 0), 0) in Oracle when a column can hold both NaN and NULL.

Why is NANVL useless on NUMBER columns?

Oracle NUMBER cannot represent NaN (only BINARY_FLOAT and BINARY_DOUBLE can), so there is never a NaN for NANVL to catch in a NUMBER column.

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.

// 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.