问题
I need to test if a numeric/float value in PostgreSQL is not a number (NaN). Note that "PostgreSQL treats NaN values as equal", so this C++ trick doesn't work. As I'm not seeing any isnan
function in PostgreSQL 9.3, here is my best attempt to make one:
create or replace function isnan(double precision) returns boolean as
$$select $1::text = 'NaN'::text$$ language sql;
Is there any better way to test for NaN
s?
回答1:
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 NaN
s 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'
$$;
回答2:
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;
回答3:
For Google BigQuery (and maybe other sql servers out there), use the following
SELECT * FROM [project:dataset.table]
WHERE IS_NAN(field) = true
来源:https://stackoverflow.com/questions/25858859/how-to-check-if-number-is-nan