Filter Active Products and Sort by Rating
List the active products with name, category, price and rating, best rated 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 all active products, showing name, category, price and rating. Order by rating descending.
A correct answer returns 113 rows with 4 columns: name, category, price, rating.
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
| name | category | price | rating |
|---|---|---|---|
First 5 of 113 rows. This is the output of the model solution on the practice database.
What you practise
- Choosing exactly which columns a query returns
- Filtering rows with a WHERE condition
- Sorting the result with ORDER BY
Hint and approach
Try the challenge first. Open these only when you need them.
Show the hint
Use WHERE status = 'active' and ORDER BY column DESC
Show the step-by-step approach
How the model solution is built, in the order the database evaluates it:
- Read from the
productstable. - Filter in
WHERE: keep the rows wherestatusequals 'active'. - Return only the columns
name,category,priceandrating. - Sort the result by
ratingdescending.
Show the model solution
SELECT name, category, price, rating FROM products WHERE status = 'active' ORDER BY rating DESC;This query produced the expected output above. Yours does not have to match it word for word: any query that returns the same rows is correct.
What to watch for
WHERE runs before ORDER BY, so discontinued products are removed first and only the remaining rows are sorted. Several products share a rating, and their relative order is not defined unless you add a second sort column.
- 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.
- WHERE. WHERE is evaluated before the SELECT list, so it cannot use a column alias defined there or the result of an aggregate.
Related SQL challenges
- Find the Amount of Each Customer's Most Recent OrderHarderMedium
- Find the Second Highest SalaryHarderHard
- Find Days Where Revenue Rose Twice in a RowHarderHard
Keep learning
- Lesson: ORDER BY
- Lesson: WHERE Clause
- Lesson: The BIG 6 SQL Clauses
- All SQL practice challenges, by difficulty and topic
- SQL interview questions with answers
- SQL Playground: run any query on the same database