SQL WHERE and ORDER BY Practice: In-Stock Products

Most real queries start by narrowing rows and ending with a sensible order. This exercise filters a small product table with two conditions and sorts the result by price. SQLite stores a yes or no flag as 1 or 0, which the starter uses for in_stock.

Before you start: What a table and a SELECT statement are.

Your task

Select the name and price of products that are in stock and cost less than 100. Order the rows from the cheapest to the most expensive.

Starter code

CREATE TABLE products (name TEXT, price INTEGER, in_stock INTEGER);
INSERT INTO products VALUES ('Pen', 20, 1), ('Notebook', 90, 1), ('Stapler', 150, 0), ('Marker', 45, 1);

-- Select affordable products that are in stock, cheapest first.

Expected result

name     | price
Pen      | 20
Marker   | 45
Notebook | 90

Compare column names and values. The text alignment of the result table can look different in the playground.

Open this exercise

Loads the starter in the workspace. Save or export existing work first. Return here for hints and the explanation.

Need a hint?

Use WHERE with in_stock = 1 AND price < 100, then add ORDER BY price.

Show the complete solution and walkthrough
CREATE TABLE products (name TEXT, price INTEGER, in_stock INTEGER);
INSERT INTO products VALUES ('Pen', 20, 1), ('Notebook', 90, 1), ('Stapler', 150, 0), ('Marker', 45, 1);

-- Select affordable products that are in stock, cheapest first.
SELECT name, price
FROM products
WHERE in_stock = 1 AND price < 100
ORDER BY price;
  1. Select only the columns you need: name and price. The Stapler row is excluded later, but the column list decides what is shown.
  2. Add WHERE in_stock = 1 AND price < 100. Both conditions must be true, so Stapler is removed because it is out of stock and costs more.
  3. Finish with ORDER BY price. The remaining rows appear as Pen 20, Marker 45 and Notebook 90.

A common mistake

Using OR instead of AND returns products that satisfy only one condition. Without ORDER BY the row order is not guaranteed, even if it looks sorted today.

Try an edge case

Rows where a filtered column is NULL do not match comparisons such as price < 100. An empty result means no row matched, not that the query failed.

Take it one step further

Sort by price descending with DESC, then add LIMIT 2 to show only the two most expensive affordable products.

Read the sql tool guide