How to check if number is NaN

落花浮王杯 提交于 2019-12-05 00:37:27

Is there any better way to test for NaNs?

Simply compare for equality:

SELECT double precision 'NaN' = double precision 'NaN';

as, per the docs you linked to, Pg treats NaNs as equal. I'm surprised by this, given that it correctly treats NULL as not equal to any other NULL, and would've expected NaN = NaN to return NULL, but ... well, it works.

Or if you want a function:

create or replace function isnan(double precision) 
language sql
immutable
returns boolean as $$
select $1 = double precision 'NaN'
$$;

Any NaN value taken with a minus sign still is a NaN value (just like a zero), so you can try this:

create or replace function isnan(double precision) returns boolean as $$
select $1 = -$1 and $1 != 0.0 $$ language sql;

or:

create or replace function isnan(double precision) returns boolean as $$
select $1 = -$1 and $1 = $1 + 1.0 $$ language sql;

As far as PostgreSQL treats NaN values greater than all non-NaN values, the following trick is possible:

create or replace function isnan(double precision) returns boolean as $$
select $1 > 0 and -$1 > 0 $$ language sql;

For Google BigQuery (and maybe other sql servers out there), use the following

SELECT * FROM [project:dataset.table]
WHERE IS_NAN(field) = true
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!