Module 2 · Filtering data

Filter rows with WHERE

By the end you will be able to show only the rows that meet a condition.

About 10 min

0 of 52 lessons

Before you start, you need

Select data with SELECT and FROM

Keep the rows that meet a condition

To see the products in stock, you do not need the whole catalogue, only the ones with units available. WHERE chooses which rows appear using a condition such as stock > 0.

The condition is checked for each row. If it is true, the row goes into the result. Mouse has 18 units, so it passes; Pro Laptop has 0, so it is left out. The excluded product is still stored in the table.

Write WHERE after FROM. To compare with text, use single quotes: category = 'Accessories'. The numbers in these examples are written without quotes.

SELECT chooses columns; WHERE chooses rows. You can filter on stock even if you only show name. The condition decides which products you see, and the SELECT list decides what information you see about them.

Minimal syntax
SELECT columns
FROM table_name
WHERE condition;

See it in action

We want to see only the products that are in stock.

Before running: Predict whether Pro Laptop, with a stock of 0, will appear when you ask for stock > 0.

SQL
SELECT name, stock
FROM products
WHERE stock > 0;
Example result: 7 rows
namestock
Mouse18
Keyboard7
Monitor 244
Headphones11
Monitor 272
SSD Drive9
Cable USB-C30
  1. Each row is checked separately. Mouse, with a stock of 18, meets stock > 0; Pro Laptop, with a stock of 0, does not.
  2. The result keeps seven products. SELECT shows the name and stock of the rows that got through.
  3. An excluded product stays in the table. If you query products without WHERE, it appears again.
  4. To filter by category, put the text value in single quotes: category = 'Accessories'.

Practice with help

Getting things wrong is part of learning: you can run your query as many times as you like and nothing is lost. If you get stuck, open a hint (each one reveals a bit more) and save the solution for last.

Guided practice

Find one category

Not started

Write a query that returns the name and stock of the products in the Accessories category.

Expected result: 3 rows with the columns name, stock, in that order. Row order does not matter.

View tables and data

Open this panel to see the full data.

Your turn

Solve this variation. Spot the part that has changed before you look for help.

Practice

Change the criterion

Not started

Show the name and stock of out-of-stock products, that is, those with a stock of 0.

Expected result: 2 rows with the columns name, stock, in that order. Row order does not matter.

View tables and data

Open this panel to see the full data.

Key takeaways

  • WHERE filters rows.
  • The condition must be true for a row to be kept.
  • Text values go in single quotes.

Next: Compare values in your filters