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.
Code
-- 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
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Which tables or CTEs does it reference?
- `readings` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.