SQLite Select
Select All Rows
Use the SELECT statement to read data from a table. SELECT * selects all the columns.
The examples on this page use this players table:
| name | score |
|---|---|
| Emil | 120 |
| Tobias | 95 |
| Linus | 150 |
| Lene | 80 |
To keep the examples short, they show only the code for the SELECT statement. Click "Try it Yourself" to see the complete code, which also creates the table and adds the rows.
Example
Select all rows from the players table:
cur.execute("SELECT * FROM players")
print(cur.fetchall())
Try it Yourself »
fetchall() returns a list with all the rows. Each row is a tuple, with the values in the same order as the columns.
Loop Through the Rows
Use a for loop to print one row at a time:
Example
Print each row on its own line:
cur.execute("SELECT * FROM players")
for row in cur.fetchall():
print(row)
Try it Yourself »
Use the Values in a Row
Each row has two values, so you can unpack them into two variables:
Example
Get the name and the score from each row:
cur.execute("SELECT * FROM players")
for name, score in cur.fetchall():
print(name, "has", score, "points")
Try it Yourself »
Select Some Columns
Instead of *, write the names of the columns you want:
Example
Select only the name column:
cur.execute("SELECT name FROM players")
for row in cur.fetchall():
print(row[0])
Try it Yourself »
Each row is still a tuple, but now with only one value, the name. row[0] gets that value.
Get One Row
Use fetchone() to get only the first row of the result:
Example
Get the first row:
cur.execute("SELECT * FROM players")
print(cur.fetchone())
Try it Yourself »
If there are no rows, fetchone() returns None.
Note: Without ORDER BY, SQLite usually returns the rows in the order they were inserted, but this is not guaranteed. You will learn how to sort the rows in the SQLite Order By chapter.
Count the Rows
Use COUNT(*) to count the rows. The result is one row with one value, so use fetchone()[0] to get the number:
Example
Count the players:
cur.execute("SELECT COUNT(*) FROM players")
count = cur.fetchone()[0]
print(count)
Try it Yourself »