Sort Products by Profit Margin (Price Minus Cost)
Return every product with its margin, the price minus the cost, largest margin first.
The challenge runs on the SQLabHub practice database (SQLite) and uses the products table. You can solve it in the browser, with nothing to install.
The task
Find products with highest (price-cost) margin.
A correct answer returns 120 rows with 11 columns: id, name, category, price, cost, stock, sku, status, rating, review_count, margin.
Tables used in this challenge
products 120 rows
id INTEGER (PK) · name TEXT · category TEXT · price REAL · cost REAL · stock INTEGER · sku TEXT · status TEXT · rating REAL · review_count INTEGER
| id | name | category | price | cost | stock | sku | status | rating | review_count |
|---|---|---|---|---|---|---|---|---|---|
The first rows of each table are shown. See how all the tables relate on the database schema page.
Expected output
| id | name | category | price | cost | stock | sku | status | rating | review_count | margin |
|---|---|---|---|---|---|---|---|---|---|---|
First 5 of 120 rows. This is the output of the model solution on the practice database.
What you practise
- Sorting the result with ORDER BY
- Deriving a new column from an expression and naming it with an alias
Hint and approach
Try the challenge first. Open these only when you need them.
Show the hint
ORDER BY expression
Show the step-by-step approach
How the model solution is built, in the order the database evaluates it:
- Read from the
productstable. - Add the calculated column
margin:price - cost. - Sort the result by
margindescending.
Model solution
Checking your session…
What to watch for
SQLite lets ORDER BY use the alias of a calculated column. WHERE cannot use it, because WHERE is evaluated before the SELECT list. This margin is in currency units; divide by price for a percentage.
- Calculated columns. Dividing one integer by another truncates the result in SQLite. Multiply one side by 1.0 to get decimals.
- ORDER BY. Without ORDER BY the row order is not guaranteed, even if it looks stable. Rows that tie on the sort columns can come back in any order.
Related SQL challenges
- Calculate the Average Value per Item of Each OrderSimilar levelHard
- Calculate Employee Tenure in Days and Sort by LongestSimilar levelHard
- Sort Products by Price, Lowest FirstEasierEasy
- Calculate Rating Variance per Product Without a VARIANCE FunctionSimilar levelHard
- Calculate Each Customer's Order Range (Max Minus Min)Similar levelHard
Keep learning
- Lesson: Comments & Aliases
- Lesson: ORDER BY
- All SQL practice challenges, by difficulty and topic
- SQL interview questions with answers
- SQL Playground: run any query on the same database