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

idnamespeciesage
1Biscuitdog3
2Mochicat5
3Pepperdog1
4LunacatNULL
5Rexdog8

Questions

  1. How many rows does SELECT * FROM pets WHERE species = 'dog'; return?
  2. What is the first name returned by SELECT name FROM pets ORDER BY age;? (Hint: think about NULL.)
  3. How many rows does SELECT name FROM pets LIMIT 2; return?
  4. What does SELECT DISTINCT species FROM pets; return?
  5. What number does SELECT COUNT(*) FROM pets; return?
  6. What number does SELECT COUNT(age) FROM pets; return?
  7. Which pets does SELECT name FROM pets WHERE age > 2 AND species = 'cat'; return?
  8. Does SELECT name FROM pets WHERE age = NULL; return Luna?
  9. What does SELECT name FROM pets ORDER BY age DESC LIMIT 1; return in PostgreSQL?
  10. What is wrong with SELECT name FROM pets WHERE species = dog;?

Answers explained

  1. 3 rows: Biscuit, Pepper and Rex.
  2. 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 FIRST or NULLS LAST to be explicit.
  3. 2 rows. Without ORDER BY, which two you get is not guaranteed. Always add ORDER BY when the order matters.
  4. dog and cat, each once.
  5. 5. COUNT(*) counts rows.
  6. 4. COUNT(column) skips NULL values, so Luna is not counted.
  7. Mochi. Luna's age is unknown, and an unknown age is not "greater than 2", so she is left out.
  8. No. Nothing is ever "equal" to NULL. Use WHERE age IS NULL.
  9. 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 NULL if you only want known ages.
  10. Missing quotes. Text values need single quotes: 'dog'. Without them, the database looks for a column called dog.

Scoring

ScoreSuggestion
0 to 4SELECT Queries in Five Short Beginner Modules
5 to 7Training Notes: Filtering and Sorting With WHERE and ORDER BY
8 to 10NULL 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.

Related pages on this site