Brightlane's inventory team is calculating a per-unit inventory cost — the listed price divided by the units currently in stock — for every product in the catalog.
Write a query to return each product's name and its per-unit inventory cost.
Assumptions:
- The
productstable has one row per product with aname, aprice, and astock_qty. - Some products have a
stock_qtyof0because they are currently sold out. - For a product with a
stock_qtyof0, the per-unit inventory cost is undefined and should appear as a missing value.
Output:
- One row per product, with columns
nameandper_unit_cost. Sold-out products will show a missing value in the second column.
Schema · ecommerce 5 tables
Run previews · Check grades
Write a query, then run it to see results here.
Worked solution Try it yourself first
SELECT
name,
price / NULLIF(stock_qty, 0) AS per_unit_cost
FROM
products The shape
NULLIF(stock_qty, 0) converts a zero stock quantity into NULL before the division happens, so the divisor is never literally 0. The arithmetic then either returns a real cost-per-unit or returns NULL. The query never crashes.
Clause by clause
SELECT name, price / NULLIF(stock_qty, 0) AS per_unit_costreturns each product's name and its per-unit inventory cost. The innerNULLIF(stock_qty, 0)is evaluated first: for a sold-out product,stock_qtyis0, the two arguments match, andNULLIFreturns NULL; for every other product it returns the recordedstock_qty. The division then runs against either a real number or against NULL, and any arithmetic with a NULL operand returns NULL.FROM productsreads every row. Sold-out products stay in the result with a missingper_unit_cost, which is exactly the output spec.
The trap
Without NULLIF, the query raises a division-by-zero error the moment PostgreSQL hits a sold-out product, and the entire result set fails. The error is not silent and it is not partial. The query returns nothing at all. NULLIF is the canonical guard for this exact case: it converts the value that would crash the expression into the value that propagates harmlessly through it. The rule is general. Any time a denominator could legitimately be zero, wrap it in NULLIF(denominator, 0) and let NULL semantics carry the missing result through.
You practiced NULLIF(denominator, 0) to guard a division — when the denominator is 0, the calculation yields missing instead of an error.