Difficulty: Beginner → Early Intermediate
Estimated time: 15–20 minutes
SQL concepts: SUM(), GROUP BY, ORDER BY, aggregation logic
Goal: Sort grouped, aggregated results by a calculated value.
The Challenge
The product manager asks:
“Which product categories generate the highest total value?”
This is a classic business question:
- Not just how much per category
- But which categories matter most
To answer it, you must aggregate first, then sort.
Database Table
products
| column_name | type | description |
|---|---|---|
| product_id | INTEGER | Unique product ID |
| name | TEXT | Product name |
| category | TEXT | Product category |
| price | DECIMAL | Product price |
Sample Data
| product_id | name | category | price |
|---|---|---|---|
| 101 | Wireless Mouse | Accessories | 24.99 |
| 102 | Mechanical Keyboard | Accessories | 89.00 |
| 103 | Webcam | Accessories | 59.99 |
| 104 | Monitor | Displays | 229.99 |
| 105 | USB-C Hub | Accessories | 34.50 |
| 106 | Laptop Stand | Workspace | 39.99 |
Your Task
Write a SQL query that returns:
- Each category
- The total value of products in that category
- Sorted from highest total value to lowest
Expected Output
| category | total_value |
|---|---|
| Accessories | 208.48 |
| Displays | 229.99 |
| Workspace | 39.99 |
(Exact order may vary depending on sample data — sorting is the key.)
Constraints
- Use
SUM() - Use
GROUP BY - Use
ORDER BY - Sort by the aggregated value
- Do not use
SELECT *
Hint (Optional)
You can sort by:
- The aggregate function itself
- Or its alias
Both are valid in most SQL dialects.
SELECT
category,
SUM(price) AS total_value
FROM products
GROUP BY category
ORDER BY total_value DESC;
Explanation
Let’s break it down:
GROUP BY category
Groups products into categories.SUM(price)
Calculates the total value per category.ORDER BY total_value DESC
Sorts categories from highest to lowest total value.
This is a foundational pattern for:
- Rankings
- Leaderboards
- Performance dashboards
- Business prioritization
Key Insight
SQL always aggregates before it sorts.
Understanding this order prevents a huge class of logical errors.
Common Mistakes
- Trying to use
ORDER BYbefore aggregation - Sorting by
priceinstead ofSUM(price) - Forgetting
DESCwhen ranking from highest to lowest
Optional Extension (Mini Bonus)
Try answering these:
- Sort categories by lowest total value first
- Show only categories with total value above 100
- Sort by total value, then alphabetically by category
Next Challenge
Beginner Challenge #29: Limiting Grouped Results (Top-N with Aggregates)
Why this challenge matters
This is where SQL starts answering strategic questions:
“What should we focus on first?”
Once learners can aggregate + sort, they’re one step away from top-N analysis, which is everywhere in analytics.
🔗 View reference solution on GitHub
(After you’ve tried the challenge)
Want more practical SQL challenges?
Subscribe to the Solve With SQL newsletter and get new problems delivered to your inbox.