Skip to main content

Why Python’s SQLite `SELECT` returns rows with a `rowcount` of `-1`

Updated 2 min readMarkdown

This SQLite SELECT returns two rows, but Python reports a rowcount of -1 before and after fetchall().

The example ran on Python 3.12.16 with the standard-library sqlite3 module. If your code processes the results only when cursor.rowcount > 0, it skips both rows in this example.

Reproduce it with two report summaries

The example runs locally with an in-memory SQLite database. It requires only Python and uses no external packages or accounts. Each row stores the number of days and the position count from a historical backtest of version 0.1.4 of the ETH adaptive ATR pullback strategy. The inputs from AlgoRover Research are (90, 274) and (365, 1135). 90-day report · 365-day report

import sqlite3

with sqlite3.connect(":memory:") as db:
    db.execute("CREATE TABLE reports (days INTEGER, positions INTEGER)")
    db.executemany(
        "INSERT INTO reports (days, positions) VALUES (?, ?)",
        [(90, 274), (365, 1135)],
    )
    cursor = db.execute("SELECT days, positions FROM reports ORDER BY days")
    before_fetch = cursor.rowcount
    rows = cursor.fetchall()
    after_fetch = cursor.rowcount
    sql_count = db.execute("SELECT COUNT(*) FROM reports").fetchone()[0]

    print({
        "before_fetch": before_fetch,
        "after_fetch": after_fetch,
        "fetched_rows": len(rows),
        "rows": [list(row) for row in rows],
        "sql_count": sql_count,
    })

The run printed the following output.

{'before_fetch': -1, 'after_fetch': -1, 'fetched_rows': 2, 'rows': [[90, 274], [365, 1135]], 'sql_count': 2}

Count fetched rows or all matching rows

For a SELECT in Python’s sqlite3, -1 means cursor.rowcount does not provide the number of result rows. Use len(rows) to count the rows Python received or if rows: to check whether it received any.

For a paginated query, len(rows) counts the rows on the page you fetched. For a simple single-table query like this one, run a separate SELECT COUNT(*) with the same WHERE filter, if any, and omit the page’s LIMIT and OFFSET to count all matching rows. If the query uses DISTINCT or GROUP BY, count the rows produced by the unpaginated query so the total reflects deduplication or grouping.

1 view

About the author

No comments yet. Be the first to comment.