NULLIF
- SQL course
- Beginner
- Lesson 62/115
- 4 min
Prevent division by zero with NULLIF.
NULLIF
NULLIF(a, b) returns NULL if a equals b, otherwise a. It is used to avoid division by zero.
SELECT total / NULLIF(count, 0) AS ort FROM orders;If count is 0 the result is NULL; no error.
total / NULLIF(count, 0) AS ort is selected from orders.
NULLIF — details
NULLIF(x, 0) prevents a divide-by-zero error. Combine with COALESCE to replace NULL with another value.
Practice NULLIF
Compute total / count from orders; avoid error when count is 0.
Starter code
-- zero-division guard
SELECT
FROM ordersSample solution
SELECT total / NULLIF(count, 0) AS ort
FROM ordersExpected output
ort 100 50
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When does NULLIF(a, b) return NULL?
- a = b ise Correct answer
- a < b ise
- Always
- a > b ise
Explanation: NULLIF returns NULL when equal.
2 Zero guard
SELECT total / ____(count, 0) FROM orders;
SELECT total / NULLIF(count, 0) FROM orders;
Explanation: NULLIF(count, 0) returns NULL when the count is 0, so you get NULL instead of a division-by-zero error.
3 NULLIF: match the terms
| Term | Meaning |
|---|---|
NULLIF |
null if equal |
COALESCE |
first filled |
IS NULL |
check |
NULL |
null |