SQL.How do GROUP BY and DISTINCT treat NULL values, even though NULL = NULL evaluates to UNKNOWN?

`GROUP BY` and `DISTINCT` treat NULL values as **not distinct from each other**, even though `NULL = NULL` evaluates to `UNKNOWN`.

- **GROUP BY:** All NULL values in a grouping column form one group.
- **DISTINCT:** Multiple NULL values in a selected column become one NULL.

For values `10, 10, NULL, NULL`:

```sql
SELECT value, COUNT(*)
FROM example
GROUP BY value;
-- 10   → 2
-- NULL → 2

SELECT DISTINCT value FROM example;
-- 10
-- NULL
```

With multiple columns, grouping and deduplication consider the **entire combination of values**.

**Interview answer:** “GROUP BY and DISTINCT use ‘not distinct’ semantics rather than ordinary equality. This allows NULL values to belong to the same group or be treated as duplicates.”
This entry was posted in Без рубрики. Bookmark the permalink.