Brightlane's warehouse manager flags products for a manual stock audit when their total inventory value exceeds $5,000.
Write a query to return the name and total inventory value for every flagged product.
Assumptions:
- The
productstable contains every item in Brightlane's catalog. - The
pricecolumn is each product's unit price; thestock_qtycolumn is the number of units currently in stock. - Inventory value is
price * stock_qty.
Output:
- One row per flagged product, with columns
nameandinventory_value.
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 * stock_qty AS inventory_value
FROM
products
WHERE
price * stock_qty > 5000 The shape
The inventory_value column doesn't exist in the products table — it's price * stock_qty. So the same calculation has to appear in two places: in the SELECT list to produce the column, and inside WHERE to filter on its value.
Clause by clause
SELECT name, price * stock_qty AS inventory_valuereturns the product name and the computed total inventory value. The multiplication runs once per surviving row, and theASalias gives the column the name the audit report expects.FROM productsis the source — every item in Brightlane's catalog with its price and current stock.WHERE price * stock_qty > 5000is the audit threshold. PostgreSQL evaluatesprice * stock_qtyfor each row, compares the result to5000, and keeps the row when the product clears the threshold. Strict>excludes the boundary, matching the prompt's "exceeds $5,000."
Why the calculation is repeated in WHERE
The alias inventory_value doesn't exist at the time WHERE runs. The evaluation order is FROM first, then WHERE, then SELECT. The alias only comes into being once SELECT finishes producing its output columns, and by then the filtering is over. Writing WHERE inventory_value > 5000 would raise an error: the name isn't defined yet.
So the calculation has to be written out again inside WHERE. PostgreSQL doesn't notice that the same expression appears twice — it evaluates each one independently against the row.
The trap
The two copies of price * stock_qty have to stay in sync. If the SELECT expression were price * stock_qty and the WHERE expression were price * units (or vice versa), the query would either error or — worse — quietly return rows that don't match what the output column actually shows. Whenever a derived value appears in both SELECT and WHERE, the two expressions must be character-for-character identical in the columns and operators they reference. The audit list is only trustworthy when the filter and the displayed value compute the same number.
You practiced filtering on a value the source table doesn't expose directly — the inventory value has to be computed from two columns and tested against the threshold. The derived-then-filtered shape recurs anywhere a condition applies to a calculation.