A filter can run without errors and still return the wrong rows. In this exercise you'll compare a faulty query with a corrected one, then change the requirement and write a third query. The eight books are fictional test data. If you are new to row filters, start with SELECT and WHERE practice.
Debugging challenge — Make the year filter apply to both genres
A reading club wants Science or Fiction books from 2010 onward, newest first. Predict which titles slip through this query before you read the answer.
SELECT title, year
FROM books
WHERE genre = 'Science' OR genre = 'Fiction' AND year >= 2010
ORDER BY year DESC, book_id;
The query returns The Red Planet (1998) and Numbers in Nature (2002) even though both predate 2010. SQL evaluates AND before OR, so every Science book qualifies regardless of its year. Group the genre choices before applying the date filter.
SELECT title, year
FROM books
WHERE (genre = 'Science' OR genre = 'Fiction') AND year >= 2010
ORDER BY year DESC, book_id;
| title | year |
|---|---|
| The Last Observatory | 2021 |
| The Silent Garden | 2015 |
| A Field Guide to Birds | 2010 |
A Field Guide to Birds is the boundary check for >= 2010. Winter Traditions checks that a recent book in another genre is still excluded.
Run the exercises in SQLite
Open a fresh SQLite database and run this setup, then paste any query from this guide to check the results yourself.
CREATE TABLE books (
book_id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
author TEXT NOT NULL,
genre TEXT NOT NULL,
year INTEGER NOT NULL,
pages INTEGER NOT NULL
);
INSERT INTO books VALUES
(1, 'The Red Planet', 'Ray Briggs', 'Science', 1998, 320),
(2, 'Rivers of Ink', 'Maya Rao', 'Fiction', 2005, 288),
(3, 'A Field Guide to Birds', 'Li Chen', 'Science', 2010, 256),
(4, 'The Silent Garden', 'Ana Souza', 'Fiction', 2015, 412),
(5, 'Numbers in Nature', 'Kavita Patel', 'Science', 2002, 199),
(6, 'Winter Traditions', 'Erik Johnson', 'History', 2018, 340),
(7, 'The Last Observatory', 'Mohan Rao', 'Science', 2021, 384),
(8, 'Tales from the Coast', 'Ruth Ortiz', 'Fiction', 1999, 210);
Try a different rule
The club splits the reading list into tracks. Keep every Fiction book. In the Science track, keep books from 2010 onward only if they have at least 300 pages. Sort by year, newest first.
Your result should list The Last Observatory (2021), The Silent Garden (2015), Rivers of Ink (2005), and Tales from the Coast (1999), in that order. The 2010 bird guide meets the year limit but has only 256 pages. The 1999 Fiction title qualifies because neither restriction applies to Fiction.
Check your filter against this one:
SELECT title, year
FROM books
WHERE genre = 'Fiction'
OR (genre = 'Science' AND year >= 2010 AND pages >= 300)
ORDER BY year DESC, book_id;
When debugging a filter, write down one row that should pass and one that should fail for each condition. Rows right on the cutoff catch mistakes such as using > when the requirement says “at least”.