Relational SQL, Schemas & Safe Querying
Relational schemas, foreign keys with ON DELETE SET NULL, LEFT JOINs, indexes, EXPLAIN QUERY PLAN, atomic transaction rollbacks, and parameterized SQLite queries tested with pytest.
Enterprise AI workflows rely on structured operational records just as much as unstructured documents. Before wiring a model, agent, or tool to a database, you need clean relational schemas, clear ownership between tables, index awareness, atomic transactions, and strict query parameterization.
In this module, you will design a relational schema with foreign keys and check constraints, query across tables with a LEFT JOIN, inspect query execution plans, test transaction rollback on a real failure, and write parameterized queries in Python verified with pytest and GitHub Actions.
What You Will Build
- Relational schema (
SCHEMA_SQL): Createusersandticketstables with primary keys,UNIQUEconstraints,CHECKconstraints, and a foreign key withON DELETE SET NULL. - Reusable SQLite connection: Open connections with
PRAGMA foreign_keys = ONenabled on every connection and close them cleanly in afinallyblock. - Parameterized reads and
LEFT JOIN: Query tickets safely with bound parameters and join user details while keeping unassigned tickets visible. - Indexes, query plans, and rollback checks: Add indexes on
tickets(status)andtickets(assignee_id), inspect query plans withEXPLAIN QUERY PLAN, and verify rollback on a real constraint failure. - Tests and CI: Verify constraints, foreign keys, rollbacks, and parameterized queries with
pytestand GitHub Actions.
1. Schemas, Foreign Keys, Indexes, Transactions, and Safe Queries
- Normalized tables and foreign keys: Store user details in
usersand referenceusers(id)fromticketsso you do not duplicate user fields across every ticket row while enforcing referential integrity (withPRAGMA foreign_keys = ONin SQLite). - Why
ON DELETE SET NULLmatters: Suppose User 42 is assigned to Ticket 105. If User 42 leaves and their account is deleted, Ticket 105 stays in the database and itsassignee_idbecomesNULL. That preserves historical ticket records for operations and auditing rather than deleting tickets or leaving broken references. ForON DELETE SET NULLto work,assignee_idmust allowNULL(do not define it asNOT NULL). ON DELETE CASCADEvs.ON DELETE SET NULL:ON DELETE CASCADEremoves dependent child rows when a parent row is deleted, whileON DELETE SET NULLkeeps the child row and clears the foreign key column toNULL. Choose based on whether historical child records should survive parent deletion.- Indexes and write overhead: An index gives the database a fast lookup structure for filtered or joined columns instead of scanning every row sequentially. However, indexes increase write overhead because every
INSERT,UPDATE, orDELETEtouching indexed columns must also update the index structures and consumes extra storage. - Transactions and rollback: A transaction groups statements so all changes commit together or none apply. When a transaction rolls back after a failure before commit, earlier uncommitted statements in that transaction are discarded so partial updates do not persist.
- Parameterized queries vs. string interpolation: Always pass user or external input as bound query parameters (
?in SQLite), never via f-strings or string concatenation. Parameterization separates SQL structure from data values, preventing SQL injection and quoting errors.
2. Step-by-Step Build Walkthrough
- Set up the
fde-00-4repository and virtual environment: Create the project structure, configure.env.example,.gitignore, andpyproject.toml, and install editable dev dependencies.macOS / Linux:
mkdir -p fde-00-4/src/fde_00_4 fde-00-4/tests cd fde-00-4 python3 -m venv .venv source .venv/bin/activate python -m pip install --upgrade pip python -m pip install -e ".[dev]" cp .env.example .envWindows (PowerShell):
mkdir fde-00-4 cd fde-00-4 py -m venv .venv .\.venv\Scripts\Activate.ps1 py -m pip install --upgrade pip py -m pip install -e ".[dev]" Copy-Item .env.example .envWindows (CMD):
mkdir fde-00-4 cd fde-00-4 py -m venv .venv .venv\Scripts\activate.bat python -m pip install --upgrade pip python -m pip install -e ".[dev]" copy .env.example .env - Open a connection, run parameterized reads and
LEFT JOIN, and close infinally: EnablePRAGMA foreign_keys = ONon every connection, keep database calls inside the activetryblock whileconnis open, and close it infinally. ALEFT JOINkeeps unassigned tickets (whereassignee_idisNULL) in the results withNULLfor the assignee name, whereas anINNER JOINwould drop unmatched rows.import sqlite3 def get_connection(db_path: str) -> sqlite3.Connection: conn = sqlite3.connect(db_path) conn.row_factory = sqlite3.Row conn.execute("PRAGMA foreign_keys = ON;") return conn conn = get_connection("app.db") try: apply_schema(conn) seed_sample_data(conn) tickets = get_tickets_by_status(conn, "open") rows = conn.execute(""" SELECT t.id, t.subject, t.status, u.full_name AS assignee FROM tickets AS t LEFT JOIN users AS u ON t.assignee_id = u.id ORDER BY t.id ASC """).fetchall() finally: conn.close()Example output (illustrative: your actual rows will depend on the sample data):
id subject status assignee 105 Delayed shipment open NULL 106 Missing invoice open Priya - Exercise: Demonstrate transaction rollback on a constraint failure: For the following exercises, open a new connection using
get_connection("app.db")and close it in afinallyblock after completing the exercise. Insidewith conn:, changes commit on success and roll back on an exception (without closing the connection). BecauseSUP-101is already seeded byseed_sample_data()andexternal_keyhas aUNIQUEconstraint, the second insert raisessqlite3.IntegrityErrorand rolls back the earlier update on ticket1.conn = get_connection("app.db") try: before = conn.execute( "SELECT status FROM tickets WHERE id = ?", (1,), ).fetchone()["status"] try: with conn: conn.execute( "UPDATE tickets SET status = ? WHERE id = ?", ("closed", 1), ) conn.execute( "INSERT INTO tickets (external_key, subject, status) " "VALUES (?, ?, ?)", ("SUP-101", "Duplicate key test", "open"), ) except sqlite3.IntegrityError: print("Transaction rolled back") after = conn.execute( "SELECT status FROM tickets WHERE id = ?", (1,), ).fetchone()["status"] print("Status before:", before) print("Status after:", after) assert after == before finally: conn.close() - Exercise: Test a foreign-key violation: Open a new connection using
get_connection("app.db")and close it in afinallyblock after completing the exercise. WithPRAGMA foreign_keys = ONactive, inserting a ticket with a user ID that does not exist in the seededuserstable (such as99999) raisessqlite3.IntegrityError.conn = get_connection("app.db") try: try: with conn: conn.execute( "INSERT INTO tickets (external_key, subject, status, assignee_id) " "VALUES (?, ?, ?, ?)", ("FK-CHECK-99999", "Invalid assignee test", "open", 99999), ) except sqlite3.IntegrityError: print("Foreign-key constraint rejected invalid assignee_id") finally: conn.close() - Exercise: Run the query plan check in SQLite: Open a new connection using
get_connection("app.db")and close it in afinallyblock after completing the exercise. Run the following SQL query against your SQLite database (viaconn.execute(...).fetchall()or thesqlite3CLI, not as a raw Python statement) and identify whether SQLite usesidx_tickets_status.conn = get_connection("app.db") try: plan_rows = conn.execute(""" EXPLAIN QUERY PLAN SELECT id, subject FROM tickets WHERE status = 'open' """).fetchall() for row in plan_rows: print(dict(row)) finally: conn.close()Look for
SEARCHusingidx_tickets_statusversus aSCAN. ASCANis not necessarily inefficient: on a small table or when a query matches a large portion of rows, scanning can be faster than using an index. An index does not guarantee the planner will select it on every query. - Run tests and commit to Git: Run the test suite locally, add
.github/workflows/pytest.ymlfor CI, and commit your work without local secrets or environment files.python -m pytest -v git status git add . git commit -m "Complete FDE module 00.4"
3. Common Pitfalls and Operational Hygiene
- Forgetting foreign key enforcement in SQLite: SQLite does not enforce foreign keys unless
PRAGMA foreign_keys = ONis executed on the connection. - Building SQL with f-strings: Never interpolate user or external values directly into SQL strings, even in internal tools or read-only helpers.
- Assuming an index is always used: Always check real queries with
EXPLAIN QUERY PLAN(orEXPLAINin PostgreSQL) and remember aSCANcan be faster on small tables.
4. Practice Assignment
Implement get_tickets_by_assignee(conn, assignee_id) in src/fde_00_4/db.py using a parameterized query, and add tests in tests/test_db.py covering:
- An existing assignee who has assigned tickets.
- An assignee (or ID) with no matching tickets.
- A deleted assignee: create a ticket assigned to a valid user, delete that user, query the ticket again, and verify that the ticket still exists and its
assignee_idisNone(NULL).
Run python -m pytest -v and push your completed fde-00-4 repository (including .github/workflows/pytest.yml) to GitHub.
5. Knowledge Check
- Why must foreign-key enforcement be enabled explicitly in SQLite, and how do you enable it on a connection?
- What is the difference between
ON DELETE CASCADEandON DELETE SET NULL, and what column requirement mustON DELETE SET NULLsatisfy? - Why must user-supplied values use SQL parameters rather than string interpolation or f-strings?
- What happens to earlier statements in a transaction when a later statement fails and the transaction rolls back?
- Why do indexes increase write overhead and storage usage?
- What is the difference between
SEARCHandSCANinEXPLAIN QUERY PLAN, and why is aSCANnot always inefficient?
Self-Review Answers
- 1. Foreign-key enforcement: SQLite disables foreign-key enforcement by default for backwards compatibility, so each connection must run
PRAGMA foreign_keys = ON;to enforce referential integrity. - 2.
ON DELETE CASCADEvs.ON DELETE SET NULL:ON DELETE CASCADEdeletes child rows when a parent row is deleted, whereasON DELETE SET NULLkeeps child rows and sets the foreign key column toNULL(requiring the column to allowNULL). - 3. Parameterized queries: Bound parameters separate SQL structure from data values, preventing SQL injection and quoting bugs even when inputs contain quotes or SQL syntax.
- 4. Transaction rollback: Rolling back discards uncommitted changes from earlier statements in that transaction so partial updates do not remain in the database.
- 5. Index write overhead: Indexes require extra storage and must be updated whenever rows are inserted, updated, or deleted on indexed columns, adding write overhead.
- 6.
SEARCHvs.SCAN:SEARCHtypically indicates an index lookup or direct key lookup, whileSCANreads rows sequentially across a table or index. ASCANis not always inefficient because a small table or a query returning most rows can be faster with a scan than an index lookup.
6. Completion Criteria
- Relational schema (
usersandtickets) created with primary keys,UNIQUEandCHECKconstraints, and a foreign key usingON DELETE SET NULL. - Reusable connection function enables
PRAGMA foreign_keys = ONand is closed cleanly in afinallyblock. - Parameterized queries (including
get_tickets_by_assignee) andLEFT JOINbehavior implemented and tested. - Transaction rollback on a real constraint failure and
EXPLAIN QUERY PLANindex check verified. - All
pytesttests pass locally and in GitHub Actions, and the repository is committed to GitHub.
Build this
Implement get_tickets_by_assignee(conn, assignee_id) in src/fde_00_4/db.py using a parameterized query, and add tests in tests/test_db.py covering an existing assignee, an assignee with no tickets, and a deleted assignee whose tickets stay in the database with assignee_id set to NULL. Run python -m pytest -v and push to GitHub with .github/workflows/pytest.yml.
Test your understanding
- Why must foreign-key enforcement be enabled explicitly in SQLite, and how do you enable it on a connection?
- What is the difference between
ON DELETE CASCADEandON DELETE SET NULL, and what column requirement mustON DELETE SET NULLsatisfy? - Why must user-supplied values use SQL parameters rather than string interpolation or f-strings?
- What happens to earlier statements in a transaction when a later statement fails and the transaction rolls back?
- Why do indexes increase write overhead and storage usage?
- What is the difference between
SEARCHandSCANinEXPLAIN QUERY PLAN, and why is aSCANnot always inefficient?
Reveal self-review answers (attempt the questions first)
- Foreign-key enforcement: SQLite disables foreign keys by default for backwards compatibility, so each connection must run
PRAGMA foreign_keys = ON;. ON DELETE CASCADEvs.ON DELETE SET NULL:ON DELETE CASCADEdeletes child rows when a parent row is deleted, whileON DELETE SET NULLkeeps child rows and sets the foreign key column toNULL(requiring the column to allowNULL).- Parameterized queries: Bound parameters separate SQL structure from data values, preventing SQL injection and quoting bugs.
- Transaction rollback: Rolling back discards uncommitted changes from earlier statements in that transaction so partial updates do not persist.
- Index write overhead: Indexes use extra storage and must be updated on inserts, updates, and deletes touching indexed columns.
SEARCHvs.SCAN:SEARCHuses an index or key lookup, whereasSCANreads sequentially; a scan can be faster on small tables or queries returning most rows.
Questions or notes on this module?