EasySQL challenge #2SELECTWHEREORDER BY

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.

Solve This SQL Challenge

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

First 3 rows of the products table
idnamecategorypricecoststockskustatusratingreview_count
1LEGO Creator Set 742pcsToys59.9919.8257SKU-000001activeNULL0
2Ergonomic Desk Mat XLOffice Supplies34.9910.85131SKU-000002active4.52
3Magnetic Phone Mount ProAutomotive24.999176SKU-000003active51

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
namecategorypricerating
Magnetic Phone Mount ProAutomotive24.995
Complete Multivitamin 90ctHealth & Beauty24.995
Laptop Pro 15"Electronics12995
Espresso Coffee MakerHome & Garden2495
Professional Car Wax KitAutomotive39.995

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:

  1. Read from the products table.
  2. Filter in WHERE: keep the rows where status equals 'active'.
  3. Return only the columns name, category, price and rating.
  4. Sort the result by rating descending.
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.
Solve This SQL Challenge

Keep learning