A Quick Self-Assessment: Can You Predict What a SELECT Returns?
Reading a query and knowing what it will return, before running it, is one of the most useful skills you can build. Use the table below, write your prediction for each query, then check the answers.
The table: snacks
| id | name | category | price_cents | in_stock |
|---|---|---|---|---|
| 1 | Apple chips | fruit | 250 | true |
| 2 | Pretzels | salty | 180 | true |
| 3 | Dried mango | fruit | 320 | false |
| 4 | Popcorn | salty | 150 | true |
| 5 | Trail mix | mixed | 400 | true |
Queries
SELECT name FROM snacks WHERE category = 'fruit';SELECT name FROM snacks WHERE in_stock = true ORDER BY price_cents;SELECT COUNT(*) FROM snacks WHERE price_cents < 200;SELECT category, COUNT(*) FROM snacks GROUP BY category;SELECT MAX(price_cents) FROM snacks;SELECT name FROM snacks ORDER BY price_cents DESC LIMIT 2;SELECT name FROM snacks WHERE category = 'fruit' OR price_cents > 350;SELECT name FROM snacks WHERE name LIKE 'P%';
Answers
- Apple chips, Dried mango. Two fruit snacks.
- Popcorn, Pretzels, Apple chips, Trail mix. Dried mango is out of stock; the rest are sorted from cheapest to most expensive.
- 2. Pretzels (180) and Popcorn (150).
- fruit 2, salty 2, mixed 1. The order of groups is not guaranteed unless you add ORDER BY.
- 400. The highest price, belonging to Trail mix.
- Trail mix, Dried mango. The two most expensive.
- Apple chips, Dried mango, Trail mix. The first two match the category; Trail mix matches the price.
- Pretzels, Popcorn.
LIKE 'P%'means "starts with P". Whether this is case-sensitive depends on the database: PostgreSQL's LIKE is case-sensitive, while SQLite and MySQL are case-insensitive for plain English letters by default.
Scoring
| Correct | What to do next |
|---|---|
| 0 to 3 | Work through Watching a SELECT Query Run, Step by Step |
| 4 to 6 | Try Quick Answers on GROUP BY and COUNT |
| 7 to 8 | Write five queries of your own for this table and predict them too |
Why prediction matters
When you predict first, a wrong result becomes interesting instead of confusing. You can ask "why did the database think that?", and the answer teaches you something specific, such as how OR combines conditions or how GROUP BY counts. Over time, you will catch mistakes in your own queries simply by reading them.
Build the table yourself
Copy this into SQLite to check your answers by running them:
CREATE TABLE snacks (id INTEGER PRIMARY KEY, name TEXT, category TEXT, price_cents INTEGER, in_stock BOOLEAN);
INSERT INTO snacks VALUES
(1,'Apple chips','fruit',250,1),(2,'Pretzels','salty',180,1),
(3,'Dried mango','fruit',320,0),(4,'Popcorn','salty',150,1),(5,'Trail mix','mixed',400,1);
SQLite stores true and false as 1 and 0, so in query 2 you can write in_stock = 1 if true is not accepted by your version.
A free learning page for beginners. Practise on a test database, never on real customer data, and check the official documentation for your database version.