Choosing Rows with WHERE
So far, your queries have shown every row of a table. Usually, though, you want only some of them: the games for small children, the orders of one customer, the reviews with five stars. To choose rows, add WHERE and a condition after FROM:
SELECT title, age_rating
FROM games
WHERE age_rating = 3;| title | age_rating |
|---|---|
| Pixel Racer | 3 |
| Moon Farm | 3 |
| Cube Logic | 3 |
| Goal Rush | 3 |
| Turbo Karts | 3 |
| Bakery Story | 3 |
| Ice Hockey Pro | 3 |
The database goes through the table row by row and checks the condition for each of them: is the age_rating of this row 3? If it is, the row goes into the result; if it isn't, the row is left out. So the result has only the 7 games that are suitable from the age of 3.
= compares two values, here the value in the column age_rating with the number 3. In SQL, a single = means “equals”, not == as in other programming languages. (SQLite understands == too, but other databases don't, so stick to =.)
The column in the condition doesn't have to be among the columns you show. This query shows only the title, and it chooses the row by its primary key, which is the surest way to find one particular row:
SELECT title
FROM games
WHERE id = 7;| title |
|---|
| Star Pilots |
WHERE has its fixed place in a query: after FROM, and before ORDER BY and LIMIT. The parts of a query always come in this order:
SELECT columns
FROM table
WHERE condition
ORDER BY columns
LIMIT number;Only SELECT and FROM are always needed. You add the others when you need them, but always in this order. The last three also work in this order: WHERE first chooses the rows, ORDER BY sorts the ones that are left, and LIMIT takes the first few of them. The two most expensive games for small children:
SELECT title, price
FROM games
WHERE age_rating = 3
ORDER BY price DESC
LIMIT 2;| title | price |
|---|---|
| Goal Rush | 50 |
| Ice Hockey Pro | 45 |
Typical mistake: WHERE after ORDER BY. The query SELECT title FROM games ORDER BY title WHERE age_rating = 3; ends with an error:
Error on line 1: near "WHERE": syntax errorSQLite didn't expect WHERE after the sorting. Move the condition in front of ORDER BY.
Instructions
Show the title and the price of the games that cost exactly $30, sorted by title:
| title | price |
|---|---|
| Castle Siege | 30 |
| Turbo Karts | 30 |
| Zombie Town | 30 |
Below it, add a query that shows the ID and the date (ordered_at) of every order placed by the customer with ID 3 (the column customer_id of the table orders), the newest order first:
| id | ordered_at |
|---|---|
| 29 | 2025-12-12 |
| 17 | 2025-03-03 |
| 8 | 2024-06-18 |
| 3 | 2024-02-29 |
Start programming for free
1/11