SolveWithSQL

SQL Beginner Challenge 28: Sorting Aggregated Results (ORDER BY with Aggregates)

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_nametypedescription
product_idINTEGERUnique product ID
nameTEXTProduct name
categoryTEXTProduct category
priceDECIMALProduct price

Sample Data

product_idnamecategoryprice
101Wireless MouseAccessories24.99
102Mechanical KeyboardAccessories89.00
103WebcamAccessories59.99
104MonitorDisplays229.99
105USB-C HubAccessories34.50
106Laptop StandWorkspace39.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

categorytotal_value
Accessories208.48
Displays229.99
Workspace39.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:

  1. GROUP BY category
    Groups products into categories.
  2. SUM(price)
    Calculates the total value per category.
  3. 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 BY before aggregation
  • Sorting by price instead of SUM(price)
  • Forgetting DESC when ranking from highest to lowest

Optional Extension (Mini Bonus)

Try answering these:

  1. Sort categories by lowest total value first
  2. Show only categories with total value above 100
  3. 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.