Brightlane's inventory team is prioritising restock decisions and wants to see the highest-value stock positions first. Stock value for a product is its unit price multiplied by stock_qty (the number of units currently in stock).
Write a query to return each product's name and stock value, sorted from highest stock value to lowest.
Assumptions:
- The
productstable contains every product in Brightlane's catalogue. - When two products share the same stock value, the one whose
namecomes first alphabetically should appear first. - The computed stock-value column should be aliased as
stock_valuein the output, and that alias can be referenced directly in theORDER BYclause.
Output:
- One row per product, with columns
nameandstock_value, sorted bystock_valuedescending, then bynameascending.
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 stock_value
FROM
products
ORDER BY
stock_value DESC,
name The shape
The alias stock_value is defined in the SELECT and reused directly in the ORDER BY — one expression, written once, used twice.
Clause by clause
SELECT name, price * stock_qty AS stock_valuecomputes the per-product stock value inline and gives it a name. The multiplication runs once per row, against that row'spriceandstock_qty, and the alias labels the resulting column so it reads as a domain quantity rather than as the raw arithmetic.FROM productsreads the catalogue.ORDER BY stock_value DESC, namesorts by the computed value descending so the highest-value stock positions land first, then alphabetises any rows whosestock_valueties. The second sort key picks the name column directly — noDESC, so it defaults to ascending.
Why this and not retyping price * stock_qty
The alternative — ORDER BY price * stock_qty DESC, name — returns the same rows in the same order. PostgreSQL evaluates the expression a second time, but the cost is invisible to the user. The reason to prefer the alias is readability: writing the expression once means there's only one place to edit if the stock-value formula ever changes, and no risk of the two copies drifting apart.
ORDER BY is one of the few clauses where a SELECT-list alias is available, and the reason is evaluation order. SELECT runs before ORDER BY, so by the time the sort happens, the alias already names a real output column. Try the same trick in WHERE, which runs before SELECT, and PostgreSQL raises an error because the alias doesn't exist yet.
You practiced sorting on a SELECT-list alias. ORDER BY runs after SELECT, so any alias defined there is available as a sort key — the recurring shape any time you want to sort by a derived value without retyping its expression.