Edexcel International Advanced Level Computer Science, point 8.3.1
SQLite is a small database engine that stores a whole database in a single file and needs no separate server. Python includes it in the sqlite3 module. Administering a database means setting up and managing its structure: creating it, defining tables, and keeping it in good order. (Check the PLS for the exact methods allowed.) The theory is in 4.1.
Connecting
import sqlite3
# opens the file (creates it if new)
conn = sqlite3.connect("club.db")
cur = conn.cursor() # used to run SQL statements
connect()returns a connection object. If the file doesn't exist, it is created.- A cursor executes SQL and holds the results of queries.
":memory:"makes a temporary database in memory (useful for testing):sqlite3.connect(":memory:").
Creating tables
cur.execute("""
CREATE TABLE IF NOT EXISTS Coach (
CoachID INTEGER PRIMARY KEY,
Name TEXT NOT NULL,
Sport TEXT
)
""")
cur.execute("""
CREATE TABLE IF NOT EXISTS Player (
PlayerID INTEGER PRIMARY KEY,
Name TEXT NOT NULL,
Team TEXT,
Age INTEGER CHECK (Age >= 16 AND Age <= 60),
CoachID INTEGER,
FOREIGN KEY (CoachID) REFERENCES Coach(CoachID)
)
""")
conn.commit()
SQLite data types
| Type | Holds |
|---|---|
INTEGER |
Whole numbers |
REAL |
Numbers with a fractional part |
TEXT |
Strings (also used for dates, as "2026-11-15") |
BLOB |
Raw binary data |
SQLite is flexible about types: it uses type affinity, so the declared type is a guide, not a strict rule.
Constraints (4.1.2)
| Constraint | Effect |
|---|---|
PRIMARY KEY |
Unique, non-empty identifier for each row (entity integrity) |
NOT NULL |
The column must have a value |
UNIQUE |
No duplicates in the column |
DEFAULT value |
Value used if none is given |
CHECK (condition) |
The value must meet a condition (domain integrity) |
FOREIGN KEY ... REFERENCES |
The value must match a primary key in another table (referential integrity) |
Composite primary key:
cur.execute("""
CREATE TABLE IF NOT EXISTS PlayerMatch (
PlayerID INTEGER,
MatchID INTEGER,
PRIMARY KEY (PlayerID, MatchID)
)
""")
Enforcing foreign keys
SQLite doesn't enforce foreign keys by default, so switch it on for each connection:
cur.execute("PRAGMA foreign_keys = ON")
Now inserting a player with a CoachID that doesn't exist raises sqlite3.IntegrityError.
Altering and dropping
# add a column
cur.execute("ALTER TABLE Player ADD COLUMN Email TEXT")
# rename a table (a spare one, so Player is kept)
cur.execute("CREATE TABLE IF NOT EXISTS Temp (X INTEGER)")
cur.execute("ALTER TABLE Temp RENAME TO OldTemp")
# delete a table
cur.execute("DROP TABLE IF EXISTS OldTemp")
conn.commit()
DROP TABLEdeletes the table and all its data permanently.- SQLite's
ALTER TABLEis limited (you can add and rename columns, but changing a column's type means making a new table).
Indexes (to speed up searches)
cur.execute("CREATE INDEX IF NOT EXISTS idx_name ON Player(Name)")
An index works like a book's index: searches on that column are faster, but inserts are slightly slower and it uses more space.
Looking at the structure
cur.execute("SELECT name FROM sqlite_master WHERE type='table'")
print(cur.fetchall()) # list of table names
cur.execute("PRAGMA table_info(Player)")
for column in cur.fetchall():
# (id, name, type, notnull, default, pk)
print(column)
Committing and closing
conn.commit()saves the changes permanently. Without it, changes can be lost.conn.rollback()undoes changes since the last commit.conn.close()ends the connection. Always close it, or usewith(which commits or rolls back automatically).
with sqlite3.connect("club.db") as conn:
conn.execute(
"INSERT INTO Coach (CoachID, Name) VALUES (1, 'Ms Khan')")
# the changes are committed here (but the connection stays open)
conn.close()
Handling errors
try:
conn = sqlite3.connect("club.db")
conn.execute("CREATE TABLE Coach (CoachID INTEGER PRIMARY KEY)")
except sqlite3.OperationalError as e:
# for example the table already exists
print("Database problem:", e)
finally:
conn.close()
Worked example
Task: set up a small library database with Book and Member tables, a Loan link table, and foreign keys switched on.
import sqlite3
conn = sqlite3.connect("library.db")
cur = conn.cursor()
cur.execute("PRAGMA foreign_keys = ON")
cur.execute("""CREATE TABLE IF NOT EXISTS Book (
BookID INTEGER PRIMARY KEY,
Title TEXT NOT NULL,
Author TEXT NOT NULL)""")
cur.execute("""CREATE TABLE IF NOT EXISTS Member (
MemberID INTEGER PRIMARY KEY,
Name TEXT NOT NULL,
Email TEXT UNIQUE)""")
cur.execute("""CREATE TABLE IF NOT EXISTS Loan (
LoanID INTEGER PRIMARY KEY,
BookID INTEGER NOT NULL REFERENCES Book(BookID),
MemberID INTEGER NOT NULL REFERENCES Member(MemberID),
DateOut TEXT NOT NULL)""")
conn.commit()
conn.close()
Loanresolves the many-to-many relationship betweenBookandMember(4.1.1).- Primary keys,
NOT NULL,UNIQUEandREFERENCESenforce the integrity constraints. IF NOT EXISTSlets the script run again without an error.commit()saves the structure, andclose()releases the file.
Exam tip: remember the sequence: connect, cursor, execute, commit, close. Know that foreign keys need PRAGMA foreign_keys = ON, and what the constraints do. DROP TABLE is permanent. Use try/except to deal with sqlite3 errors.
Check yourself
What does sqlite3.connect("data.db") do if the file doesn't exist?
It creates a new, empty database file with that name.
Why must you call commit()?
It saves the changes permanently; without it, changes made since the last commit can be lost.
Which statement switches on foreign key checking in SQLite?
PRAGMA foreign_keys = ON.
What does a CHECK constraint do?
It makes sure that values in a column meet a condition, such as an age between 16 and 60 (domain integrity).
What does DROP TABLE do?
It permanently deletes the table and all its data.