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.
Code
-- 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
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.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.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
- What objects does the SQL involve?
- `readings` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.