Running a SELECT from code and fetching rows
Returns every row from the SELECT that cursor.execute() ran, as a list of tuples. An empty result gives an empty list []. fetchone() returns just one row.
Understanding Running a SELECT from code and fetching rows in QCE Digital Solutions Unit 2
What it does: fetchone() gives one tuple such as (1, 'Pencil'), not a list of tuples. An empty result from fetchall() is [], so comparing rows to [] detects that nothing was found. execute() sends the SQL to the database. fetchall() takes no SQL; it only collects the rows afterwards. By default, sqlite3 returns each row as a tuple, in the same order as the columns in the SELECT. fetchall() returns all the rows of the last query as a list of tuples, and [] when no rows match.
Common mistakes: A for statement must end with a colon. Line 4 should be 'for row in rows:' so it can loop over the list of tuples returned by fetchall(). fetchall() returns a normal Python list, and lists have no .len() method. Use the len() function: print(len(rows)) to count the rows.
Free printable worksheet with full answer key — or add this module to a class and your students practise it interactively.
This module's key terms are also in a printable crossword (Modules 337–409) and word search (Modules 234–409).
Take this worksheet further — free with Cloodit
Each concept is reinforced from every angle — learned, then applied, then tested.
Cloodit turns curriculum-aligned coding content into journeys students work through one biome at a time.
Over 100 of them, across seven natural biomes.
Turns their work into revision material ready for Flash Cards and Exam study.
Live, competitive practice for the start of the lesson or a teacher-led lesson finisher.
Honour your top performers, or encourage a student who's trying hard — ready to print in seconds.
Quick Questions
Match the Pairs
Key Term
cursor.fetchall()Fill in the Blanks
Spot the Error
Student with a class code? Join your class →