GROUP BY Treats NULL Keys As One Group

GROUP BY treats NULL as one group key: every NULL row lands in a single bucket, even though no WHERE comparison can ever match a NULL value.

SqlData Integrity

Code

snippet
-- GROUP BY 把 NULL 当作一个独立的分组键值:所有 NULL 键的行聚成一行,
-- 与 WHERE 里"NULL 参与比较直接消失"的行为完全不同
WITH readings AS (
    SELECT * FROM (VALUES
        ('sensor-a', 21.5),
        (NULL,       19.0),
        (NULL,       23.0),
        ('sensor-b', 20.0)
    ) AS t(sensor_id, temperature)
)
SELECT
    sensor_id,
    COUNT(*)         AS readings,
    AVG(temperature) AS avg_temperature
FROM readings
GROUP BY sensor_id
ORDER BY sensor_id NULLS FIRST;

-- 对照:WHERE sensor_id = NULL 永远返回空集(要用 IS NULL),
-- 但 GROUP BY 照样把 NULL 键的行聚进同一个桶

How the snippet works

The statement is SELECT, touching readings.

What the statements actually assemble: a CTE (WITH … AS) that names an intermediate result before the main query; COUNT, AVG aggregation; a GROUP BY that collapses matching rows into one output row per group; an ORDER BY that fixes the output order.

Using it

Run the statement against the readings table.

Key statements

WITH readings AS (
SELECT * FROM (VALUES
('sensor-a', 21.5),
(NULL,       19.0),
(NULL,       23.0),
('sensor-b', 20.0)
) AS t(sensor_id, temperature)
)
SELECT
sensor_id,
COUNT(*)         AS readings,
AVG(temperature) AS avg_temperature
FROM readings
GROUP BY sensor_id
ORDER BY sensor_id NULLS FIRST;

Interactive Tools for This Topic

FAQ

What objects does the SQL involve?
`readings` — referenced directly, no join needed.