SQL.How do aggregate functions handle NULL, and what is the difference between COUNT(*), COUNT(column), and COUNT(DISTINCT column)?

Most common aggregates (`SUM`, `AVG`, `MIN`, `MAX`, `COUNT(column)`) **ignore NULL values**.

| Expression | What it counts |
|---|---|
| `COUNT(*)` | All rows, including rows containing NULL |
| `COUNT(column)` | Non-NULL values in that column |
| `COUNT(DISTINCT column)` | Unique non-NULL values in that column |

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

```sql
COUNT(*)                -- 4
COUNT(column)           -- 3
COUNT(DISTINCT column)  -- 2
SUM(column)             -- 40
AVG(column)             -- 40 / 3, not 40 / 4
```

**Edge case:** With no non-NULL input values, `SUM`, `AVG`, `MIN`, and `MAX` return `NULL`; `COUNT(column)` returns `0`.

**Interview answer:** “Most aggregate functions ignore NULL. COUNT(*) counts rows, COUNT(column) counts non-NULL values, and COUNT(DISTINCT column) counts unique non-NULL values.”
This entry was posted in Без рубрики. Bookmark the permalink.