# COALESCE() and IFNULL(): replace NULL with a default

Source: https://sqlstreak.com/sql/functions/coalesce · Tested on PostgreSQL 18.6 and SQLite 3.54.1; results generated 2026-11-22.


**Short answer:** `COALESCE(a, b, …)` returns the first argument that isn't NULL: `COALESCE(breed, 'mixed')` shows 'mixed' where the breed is missing. It works in both databases; SQLite also has `IFNULL(a, b)` for exactly two arguments, which PostgreSQL doesn't.

## Syntax

- PostgreSQL: `COALESCE(value1, value2, …)` (COALESCE: yes. IFNULL: no)
- SQLite: `COALESCE(value1, value2, …)  /  IFNULL(value, default)` (Both)

## Examples

### A label for missing breeds

```sql
SELECT name, COALESCE(breed, 'mixed') AS breed
FROM pets
ORDER BY id
LIMIT 6;
```

Result (both engines):

| name | breed |
| --- | --- |
| Biscuit | Beagle |
| Mochi | Siamese |
| Pickles | mixed |
| Luna | mixed |
| Waffles | Holland Lop |
| Bruno | Boxer |

### The first contact detail that exists

Phone if there is one (blank counts as missing), otherwise the email.

```sql
SELECT id, COALESCE(NULLIF(TRIM(phone), ''), LOWER(TRIM(email))) AS contact
FROM adoption_requests
ORDER BY id
LIMIT 6;
```

Result (both engines):

| id | contact |
| --- | --- |
| 1 | 555-0101 |
| 2 | ben@mail.com |
| 3 | ana@mail.com |
| 4 | 555-0104 |
| 5 | 555-0105 |
| 6 | cara@mail.com |

### Zero instead of NULL after a LEFT JOIN

Customers who never ordered get a NULL total; COALESCE turns it into 0.

```sql
SELECT c.name, COALESCE(SUM(oi.quantity), 0) AS items_bought
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
LEFT JOIN order_items oi ON oi.order_id = o.id
GROUP BY c.id, c.name
ORDER BY items_bought, c.name
LIMIT 5;
```

Result (both engines):

| name | items_bought |
| --- | --- |
| Diego Santos | 0 |
| Nora Lindqvist | 0 |
| Priya Nair | 2 |
| Tomás Herrera | 3 |
| Lena Fischer | 5 |

## Edge cases, measured on both engines

| Case | PostgreSQL | SQLite |
| --- | --- | --- |
| First non-NULL | 'x' | 'x' |
| Several NULLs first | 3 | 3 |
| An empty string isn't NULL | '' | '' |
| All NULL | NULL | NULL |
| Mixed types | error: invalid input syntax for type integer: "a" | 1 |
| IFNULL | error: function ifnull(unknown, integer) does not exist | 0 |

## Common mistakes

- Expecting COALESCE to treat '' as missing: an empty string is a value. Combine with NULLIF: `COALESCE(NULLIF(x, ''), 'none')`.
- Mixing types: PostgreSQL wants all arguments to share a type (the matrix shows the error); SQLite returns whatever comes first.
- Using IFNULL or ISNULL in PostgreSQL: neither exists there.
