Skip to content
Quantoros

What does SUM(NULL) return?

SQLLevel: FoundationAggregations Basics

What does SUM(NULL) return?

Hints
  • Distinguish a missing value from zero, an empty string and false.
  • Test comparison, aggregation and filtering on a tiny missing-value example.

Answer

SUM пропускает NULL. Если входных значений, отличных от NULL, нет, результат — NULL, а не 0. Так же ведут себя AVG, MIN и MAX, но не COUNT: COUNT(column) в этом случае возвращает 0.

SELECT SUM(x), COUNT(x), COALESCE(SUM(x), 0)
FROM (VALUES (NULL::integer), (NULL::integer)) AS t(x);
-- NULL, 0, 0

Замена NULL на ноль — решение о смысле данных, поэтому COALESCE следует добавлять осознанно.

Source and licence: SQL Interview Questions — Arda Kocadoru · MIT · answer: Quantoros editorial

Related questions