Edexcel International Advanced Level Computer Science, point 8.3.3
Retrieving data means reading rows from the database with a SELECT statement, and using the results in Python. (Check the PLS for the exact methods allowed.)
The examples use this data:
import sqlite3
conn = sqlite3.connect(":memory:")
cur = conn.cursor()
cur.execute("CREATE TABLE Player (PlayerID INTEGER PRIMARY KEY, "
"Name TEXT, Team TEXT, Goals INTEGER)")
sql = "INSERT INTO Player (Name, Team, Goals) VALUES (?, ?, ?)"
cur.executemany(sql, [("Mia", "Reds", 4), ("Leo", "Blues", 7),
("Ava", "Reds", 2), ("Kai", "Blues", 5)])
conn.commit()
The SELECT statement
SELECT column1, column2 FROM table;
SELECT * FROM table; -- every column
SELECTnames the columns wanted.*means all of them.FROMnames the table.- Selecting only the columns you need is more efficient.
Running a query and fetching results
cur.execute("SELECT Name, Goals FROM Player")
execute runs the query. Then fetch the results in one of three ways.
fetchall(): every row, as a list
cur.execute("SELECT Name, Goals FROM Player")
rows = cur.fetchall()
print(rows) # [('Mia', 4), ('Leo', 7), ('Ava', 2), ('Kai', 5)]
for name, goals in rows:
print(name, goals)
Each row is a tuple, and the whole result is a list of tuples. An empty result is [].
fetchone(): the next row
cur.execute("SELECT Name, Goals FROM Player WHERE PlayerID = ?", (2,))
row = cur.fetchone()
print(row) # ('Leo', 7)
- Returns one tuple, or
Noneif there are no (more) rows. - Use it when you expect a single row (a lookup by primary key).
Looping over the cursor
for row in cur.execute("SELECT Name FROM Player"):
# row is a tuple: row[0] is the first column
print(row[0])
- This handles the rows one at a time, which is good for large results.
fetchmany(n)
cur.execute("SELECT Name FROM Player")
print(cur.fetchmany(2)) # [('Mia',), ('Leo',)]
Selecting with a condition
Use WHERE with ? placeholders (8.3.2):
team = "Blues"
cur.execute("SELECT Name FROM Player WHERE Team = ?", (team,))
print(cur.fetchall()) # [('Leo',), ('Kai',)]
(More conditions, ordering and grouping are in 8.3.4.)
Using the results
cur.execute("SELECT Goals FROM Player")
goals = [row[0] for row in cur.fetchall()] # flatten to a list
print(sum(goals)) # 18
Named columns: to access values by column name, set a row factory:
conn.row_factory = sqlite3.Row
cur = conn.cursor()
cur.execute("SELECT * FROM Player WHERE PlayerID = 1")
row = cur.fetchone()
print(row["Name"], row["Goals"]) # Mia 4
conn.row_factory = None # back to plain tuples for the rest of this page
cur = conn.cursor()
Retrieving from more than one table: JOIN
When data is spread across linked tables (4.1), a JOIN combines rows using the key.
cur.execute("CREATE TABLE Coach "
"(CoachID INTEGER PRIMARY KEY, CName TEXT)")
cur.execute("ALTER TABLE Player ADD COLUMN CoachID INTEGER")
cur.execute("INSERT INTO Coach VALUES (1, 'Ms Khan'), (2, 'Mr Ito')")
cur.execute("UPDATE Player SET CoachID = 1 WHERE Team = 'Reds'")
cur.execute("UPDATE Player SET CoachID = 2 WHERE Team = 'Blues'")
cur.execute("""SELECT Player.Name, Coach.CName
FROM Player
INNER JOIN Coach
ON Player.CoachID = Coach.CoachID""")
print(cur.fetchall())
# [('Mia', 'Ms Khan'), ('Leo', 'Mr Ito'),
# ('Ava', 'Ms Khan'), ('Kai', 'Mr Ito')]
INNER JOIN ... ONmatches rows where the foreign key equals the primary key.- Qualify the column names with the table name (
Player.Name) when they could be ambiguous.
Aggregate values
cur.execute("SELECT COUNT(*), AVG(Goals), MAX(Goals) FROM Player")
print(cur.fetchone()) # (4, 4.5, 7)
Aggregate functions: COUNT, SUM, AVG, MIN, MAX.
Worked example
Task: write a function that returns a player's goals by name, giving None if the player isn't found, and a function that returns all names as a Python list.
def get_goals(conn, name):
sql = "SELECT Goals FROM Player WHERE Name = ?"
cur = conn.execute(sql, (name,))
row = cur.fetchone()
return row[0] if row else None
def all_names(conn):
cur = conn.execute("SELECT Name FROM Player")
return [row[0] for row in cur.fetchall()]
print(get_goals(conn, "Leo")) # 7
print(get_goals(conn, "Zed")) # None
print(all_names(conn)) # ['Mia', 'Leo', 'Ava', 'Kai']
fetchone()is used because at most one row is expected, andNoneis checked to avoid an error.fetchall()returns a list of tuples, and a list comprehension takes the first item from each.- The
?placeholder keeps the query safe.
Exam tip: know what each fetch method returns (fetchone gives a tuple or None, fetchall gives a list of tuples). Each row is a tuple, so you index it (row[0]). Check for None/empty results before using them. Use placeholders in the WHERE clause.
Check yourself
What does fetchall() return?
A list of all the remaining rows, with each row as a tuple (an empty list if there are none).
What does fetchone() return when there are no more rows?
None.
What does SELECT * FROM Player do?
It retrieves every column of every row from the Player table.
What is the purpose of a JOIN?
To combine rows from two tables by matching a foreign key with a primary key, so linked data can be retrieved together.
How would you get the average of a column in SQL?
Use the AVG aggregate function, for example SELECT AVG(Goals) FROM Player.