HardSQL challenge #224CALCULATIONORDER BYANALYSIS

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.

Solve This SQL Challenge

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

First 3 rows of the products table
idnamecategorypricecoststockskustatusratingreview_count
1Play Kitchen DeluxeToys1786.38589.51257SKU-000001active457
2Micro-Cut Paper Shredder 8-SheetOffice Supplies907.93281.46131SKU-000002active2.5447
34K Dual Dash CameraAutomotive568.89204.8176SKU-000003active4.129

The first rows of each table are shown. See how all the tables relate on the database schema page.

Expected output

Expected output of the challenge
idnamecategorypricecoststockskustatusratingreview_countmargin
108Succulent Plant SetHome & Garden1990.16616.95107SKU-000108discontinued42241373.21
68Single Origin Coffee 500gFood & Beverage1991.75657.28195SKU-000068active4.71311334.47
28Japanese Green Tea 50 bagsFood & Beverage1937.51620488SKU-000028active2.751317.51
65Waterproof Hiking BootsSports & Outdoors1769.01566.08164SKU-000065active4.14811202.9299999999998
1Play Kitchen DeluxeToys1786.38589.51257SKU-000001active4571196.8700000000001

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:

  1. Read from the products table.
  2. Add the calculated column margin: price - cost.
  3. Sort the result by margin descending.

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.
Solve This SQL Challenge

Keep learning