Course contentsShow
← Data Science
Lesson 1095 of 2,14528. Working with Databases from PythonFree lesson

Fetching Single Results with fetchone()

Retrieve one row at a time from query results and understand when this method is appropriate.

Fetching Single Results with fetchone()

You'll learn how to retrieve query results one row at a time using fetchone(), and when this approach makes sense for your workflow.

After executing a query with a cursor object, you have several ways to retrieve the results. The fetchone() method is the most granular approach—it returns exactly one row from the result set as a tuple (or None if no rows remain).

How It Works

Think of fetchone() like taking one card at a time from a deck. Each call moves an internal pointer forward, giving you the next available row. If you call it again, you get the next row, and so on, until the results are exhausted.

import sqlite3

conn = sqlite3.connect('sales.db')
cursor = conn.cursor()

cursor.execute("SELECT name, revenue FROM products ORDER BY revenue DESC")

# Get the first row
top_product = cursor.fetchone()
print(top_product)  # e.g., ('Widget A', 5000)

# Get the second row
second_product = cursor.fetchone()
print(second_product)  # e.g., ('Widget B', 4200)

# Keep going until None is returned
third_product = cursor.fetchone()

When to Use fetchone()

This method shines when:

  • You only need one specific result (like the top row)
  • You're processing rows one at a time in a memory-efficient manner
  • You want explicit control over iteration (perhaps with conditional logic between fetches)

Avoid fetchone() when you know you need all results upfront—repeatedly calling it in a loop is less efficient than using fetchall() or iterating directly over the cursor.

Key Takeaway: fetchone() retrieves a single row from your query results and advances the cursor position, ideal for processing results incrementally or when you only need the first result.