SQL.How does NULL propagate through arithmetic expressions, and how can COALESCE and NULLIF help handle missing values and division by zero?

Arithmetic involving `NULL` produces **NULL**:

```sql
10 + NULL  -- NULL
10 * NULL  -- NULL
```

**COALESCE** returns the first non-NULL argument. Use it to provide a default when that default makes business sense:

```sql
salary + COALESCE(bonus, 0)
-- Treats a missing bonus as zero
```

**NULLIF(a, b)** returns `NULL` if the arguments are equal; otherwise, it returns `a`. Use it to avoid division by zero:

```sql
amount / NULLIF(quantity, 0)
-- If quantity is zero, division returns NULL instead of an error
```

You can combine them:

```sql
COALESCE(amount / NULLIF(quantity, 0), 0)
-- Replaces a NULL result with zero
```

**Pitfall:** A missing or undefined result is not necessarily zero. Only substitute zero when it is meaningful.

**Interview answer:** “NULL propagates through arithmetic expressions. COALESCE supplies defaults for missing values, while NULLIF can turn a zero denominator into NULL to prevent division-by-zero errors.”
This entry was posted in Без рубрики. Bookmark the permalink.