SQL Challenger
0 of 250 complete

Lessons

0 of 250 complete

Saved in this browser

Lesson 207 of 250

Hard

Build a sell-through report for every album

Your task

Return title, copies_sold, and sell_through_pct for every album. Round the percentage to one decimal and return NULL when sold copies plus stock is zero. Sort by album ID.

Sell-through here means sold copies divided by sold copies plus current stock.

Sample data

Choose a table
idtitlegenrepricestock
1Night BusJazz187
2Static BloomIndie224
3Soft CircuitElectronic240
4Blue HourJazz163
5CoastlineIndie198
6Low TideAmbient212

Expected output

titlecopies_soldsell_through_pct
Night Bus541.7
Static Bloom342.9
Soft Circuit0NULL
Blue Hour240
Coastline111.1
Low Tide00
Show a hint

Sum sales by album before joining them to inventory. Use COALESCE for missing sales and NULLIF for the denominator.

Optimization and capstones guide

Compare equivalent filters

A function on an indexed column can hide the key from a direct range lookup. The two predicates here select the same January dates in this dataset. Compare the plans and look for a constrained SEARCH on the second query.

EXPLAIN QUERY PLAN
SELECT id FROM receipts WHERE STRFTIME('%Y-%m', sold_on) = '2025-01';

EXPLAIN QUERY PLAN
SELECT id FROM receipts
WHERE sold_on >= '2025-01-01' AND sold_on < '2025-02-01';

Continue from a stable key

OFFSET skips entries before the requested page. With keyset pagination, use the last ID from the previous page as a boundary. The order and boundary must use the same key. Use a unique tie-breaker if the leading sort column can repeat.

EXPLAIN QUERY PLAN
SELECT id, title FROM catalog
WHERE id > 500
ORDER BY id
LIMIT 5;

Summarize first, compare second

Start reports by deciding what one result row represents. This report groups receipts by month, then compares monthly totals with LAG. If February has no receipts, the next row compares with January. Generate a calendar CTE and left join it when gaps need to appear explicitly.

WITH monthly AS (
  SELECT STRFTIME('%Y-%m', sold_on) AS month, SUM(amount) AS total
  FROM receipts
  GROUP BY month
)
SELECT month, total, total - LAG(total) OVER (ORDER BY month) AS change
FROM monthly
ORDER BY month;
SQLiteCtrl / ⌘ + Enter

Press Control+Space for SQL suggestions. Use the arrow keys to select an option and Enter to insert it.

Results

Loading SQLite…