Start learning free

LESSON 37 OF 173 · BACKEND: SQL

Filter Rows with WHERE in Java

Practice

So far every query returned all 8 products. To keep only some rows, add a WHERE piece after FROM. It holds a condition: the database checks it on every row and keeps the rows where it is true, like an if inside a for loop.

The comparisons are the ones you know from Java: <, <=, > and >=. The condition can test any column of the table, even one you don't select. This keeps the products with 100 or more in stock, the Pen and the Gift card:

String query = "";
query += "SELECT name ";
query += "FROM products ";
query += "WHERE stock >= 100 ";

The clauses always come in this order: SELECT, FROM, WHERE. Watch the edge of the range: <= keeps a value equal to the limit, < doesn't.

Your query must print the products that cost 10 or less:

name | price
Notebook | 7
Pen | 2
Stapler | 9
(3 rows)

Your task: add to query the pieces that read each product's name and price from the products table, and keep only the products whose price is 10 or less.


Assignment
Follow the Coding Tutorial to choose the columns, read the products table, then filter its rows with a WHERE condition.


Hint
The WHERE piece goes after FROM. "10 or less" means the price may also equal 10, so use <=, written with no space between the two symbols.


STEP 1 OF 3
    Ctrl + Enter to check

    Sql Where in Java

    Keep going with Java1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free