How Much Do You Know About SELECT Queries?
SELECT is the statement you will write most. This quiz uses one tiny made-up table so you can work out each answer by reading. Take your time; there is no clock.
The practice table: pets
| id | name | species | age |
|---|---|---|---|
| 1 | Biscuit | dog | 3 |
| 2 | Mochi | cat | 5 |
| 3 | Pepper | dog | 1 |
| 4 | Luna | cat | NULL |
| 5 | Rex | dog | 8 |
Questions
- How many rows does
SELECT * FROM pets WHERE species = 'dog';return? - What is the first name returned by
SELECT name FROM pets ORDER BY age;? (Hint: think about NULL.) - How many rows does
SELECT name FROM pets LIMIT 2;return? - What does
SELECT DISTINCT species FROM pets;return? - What number does
SELECT COUNT(*) FROM pets;return? - What number does
SELECT COUNT(age) FROM pets;return? - Which pets does
SELECT name FROM pets WHERE age > 2 AND species = 'cat';return? - Does
SELECT name FROM pets WHERE age = NULL;return Luna? - What does
SELECT name FROM pets ORDER BY age DESC LIMIT 1;return in PostgreSQL? - What is wrong with
SELECT name FROM pets WHERE species = dog;?
Answers explained
- 3 rows: Biscuit, Pepper and Rex.
- It depends on the database. PostgreSQL puts NULLs last in ascending order by default, so the first name is Pepper (age 1). MySQL and SQLite put NULLs first, so Luna comes first. A useful lesson: NULL ordering is not the same everywhere. PostgreSQL lets you write
NULLS FIRSTorNULLS LASTto be explicit. - 2 rows. Without ORDER BY, which two you get is not guaranteed. Always add ORDER BY when the order matters.
- dog and cat, each once.
- 5.
COUNT(*)counts rows. - 4.
COUNT(column)skips NULL values, so Luna is not counted. - Mochi. Luna's age is unknown, and an unknown age is not "greater than 2", so she is left out.
- No. Nothing is ever "equal" to NULL. Use
WHERE age IS NULL. - Luna. In PostgreSQL, NULLs come first in descending order by default, so the unknown age sorts to the top. In MySQL and SQLite you would get Rex. Add
WHERE age IS NOT NULLif you only want known ages. - Missing quotes. Text values need single quotes:
'dog'. Without them, the database looks for a column called dog.
Scoring
| Score | Suggestion |
|---|---|
| 0 to 4 | SELECT Queries in Five Short Beginner Modules |
| 5 to 7 | Training Notes: Filtering and Sorting With WHERE and ORDER BY |
| 8 to 10 | NULL Explained: The Value That Means Unknown |
Why NULL appears so often here
Questions 2, 6, 7, 8 and 9 all involve NULL. That is on purpose. NULL behaves differently from ordinary values, and it is behind many beginner surprises. Once you are comfortable with it, a lot of puzzling query results suddenly make sense.
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.