Before continuing: This entry is part of the NULL guide. If you are new to the topic, start with IS NULL / IS NOT NULL.
NULLIF example
We want the average stock of available products only. We turn the zeros into NULL because AVG ignores null values:
SELECT ROUND(AVG(NULLIF(stock, 0)), 2) AS average_available_stock
FROM products;What to look for: If a product has stock = 0, NULLIF(stock, 0) returns NULL; with stock = 7, returns 7. That keeps zeros out of the average without deleting any products.
Check the result with small data
Two items have positive stock and one has zero.
WITH products(name, stock) AS (
VALUES ('Mouse',0),('Keyboard',5),('Monitor',10)
)
SELECT COUNT(NULLIF(stock,0)) AS in_stock
FROM products;| in_stock |
|---|
| 2 |
NULLIF(stock, 0) turns the zero into NULL. COUNT ignores that NULL and counts only the two products in stock.
Check your understanding: What would COUNT(*) return for the same products?
Show answer
3. COUNT(*) counts rows without looking at their values, so it also includes the product with stock 0.
How NULLIF is used
You can read its logic like this: “if valor1 and valor2 are equal, return NULL; otherwise keep valor1”.
Common mix-ups with NULLIF
Using it without being sure what the value means
SELECT AVG(NULLIF(price, 0)) FROM products;Excluding prices of zero is only right if zero means “not provided”. If zero means a free product, removing it from the average changes the question. Decide first what the value means in your data.
Avoiding an impossible division without inventing its result
If you calculate sales per visit, a denominator of zero does not mean a rate of zero: the ratio is undefined. NULLIF(visitas, 0) turns that case into a null denominator so the expression returns an unknown result. Show the visit count or a quality flag next to the metric if readers need to tell a valid figure apart from an impossible ratio.
Replacing that null result with zero afterwards using COALESCE is a separate decision. On a dashboard it can make a campaign with no visits look like one with visits but no sales. If you then average across campaigns, that zero changes the denominator of the average. Decide first how to exclude or flag the observations that cannot be compared.
The operator can also turn a legacy marker, such as an empty string, into null, but only when the two values are equal under the engine's comparison rules. It does not trim spaces or catch invalid values other than the sentinel you chose. Nor does it fix integer division: even with the zero handled, the types of the numerator and denominator still decide the precision.
Technical questions: PostgreSQL: conditional expressions (opens in a new tab).