Numeric NaN Sorts Above All Values

Numeric NaN sorts above every finite value and equals itself, so max() picks NaN and unique keys treat it as one ordinary sentinel.

SqlData Integrity

Code

snippet
-- numeric 的 NaN sorts above all values:这是文档化的排序语义,便于哨兵值设计
WITH readings(value, label) AS (
    VALUES
        (1.5::numeric, 'low'),
        (999999::numeric, 'big'),
        ('NaN'::numeric, 'not a number')
)
SELECT
    label,
    value
FROM readings
ORDER BY value DESC, label;

-- NaN 与自身相等(对照 float 的 NaN),因此可作聚合键与唯一键
SELECT 'NaN'::numeric = 'NaN'::numeric AS nan_equals_itself;
SELECT max(value) = 'NaN'::numeric AS max_picks_nan FROM readings;
-- 双精度 NaN 参与等值比较则与自身不相等
SELECT 'NaN'::double precision = 'NaN'::double precision AS float_nan_unequal;

Inside the snippet

What runs here is SELECT — readings are the objects involved.

Mechanically, the statements are built from: a CTE (WITH … AS) that names an intermediate result before the main query; MAX aggregation; an ORDER BY that fixes the output order.

Putting it to use

The readings table is the working surface here.

Lines that carry the file

WITH readings(value, label) AS (
    VALUES
        (1.5::numeric, 'low'),
        (999999::numeric, 'big'),
        ('NaN'::numeric, 'not a number')
)
SELECT
    label,
    value
FROM readings
ORDER BY value DESC, label;
SELECT 'NaN'::double precision = 'NaN'::double precision AS float_nan_unequal;
SELECT max(value) = 'NaN'::numeric AS max_picks_nan FROM readings;

Interactive Tools for This Topic

FAQ

Which tables or CTEs does it reference?
`readings` — referenced directly, no join needed.