MODULE 00.4 · PUBLISHED · ~1–2h

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): Create users and tickets tables with primary keys, UNIQUE constraints, CHECK constraints, and a foreign key with ON DELETE SET NULL.
  • Reusable SQLite connection: Open connections with PRAGMA foreign_keys = ON enabled on every connection and close them cleanly in a finally block.
  • 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) and tickets(assignee_id), inspect query plans with EXPLAIN QUERY PLAN, and verify rollback on a real constraint failure.
  • Tests and CI: Verify constraints, foreign keys, rollbacks, and parameterized queries with pytest and GitHub Actions.

1. Schemas, Foreign Keys, Indexes, Transactions, and Safe Queries

  • Normalized tables and foreign keys: Store user details in users and reference users(id) from tickets so you do not duplicate user fields across every ticket row while enforcing referential integrity (with PRAGMA foreign_keys = ON in SQLite).
  • Why ON DELETE SET NULL matters: Suppose User 42 is assigned to Ticket 105. If User 42 leaves and their account is deleted, Ticket 105 stays in the database and its assignee_id becomes NULL. That preserves historical ticket records for operations and auditing rather than deleting tickets or leaving broken references. For ON DELETE SET NULL to work, assignee_id must allow NULL (do not define it as NOT NULL).
  • ON DELETE CASCADE vs. ON DELETE SET NULL: ON DELETE CASCADE removes dependent child rows when a parent row is deleted, while ON DELETE SET NULL keeps the child row and clears the foreign key column to NULL. 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, or DELETE touching 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

  1. Set up the fde-00-4 repository and virtual environment: Create the project structure, configure .env.example, .gitignore, and pyproject.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 .env

    Windows (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 .env

    Windows (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
  2. Open a connection, run parameterized reads and LEFT JOIN, and close in finally: Enable PRAGMA foreign_keys = ON on every connection, keep database calls inside the active try block while conn is open, and close it in finally. A LEFT JOIN keeps unassigned tickets (where assignee_id is NULL) in the results with NULL for the assignee name, whereas an INNER JOIN would 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
  3. 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 a finally block after completing the exercise. Inside with conn:, changes commit on success and roll back on an exception (without closing the connection). Because SUP-101 is already seeded by seed_sample_data() and external_key has a UNIQUE constraint, the second insert raises sqlite3.IntegrityError and rolls back the earlier update on ticket 1.
    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()
  4. Exercise: Test a foreign-key violation: Open a new connection using get_connection("app.db") and close it in a finally block after completing the exercise. With PRAGMA foreign_keys = ON active, inserting a ticket with a user ID that does not exist in the seeded users table (such as 99999) raises sqlite3.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()
  5. Exercise: Run the query plan check in SQLite: Open a new connection using get_connection("app.db") and close it in a finally block after completing the exercise. Run the following SQL query against your SQLite database (via conn.execute(...).fetchall() or the sqlite3 CLI, not as a raw Python statement) and identify whether SQLite uses idx_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 SEARCH using idx_tickets_status versus a SCAN. A SCAN is 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.

  6. Run tests and commit to Git: Run the test suite locally, add .github/workflows/pytest.yml for 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 = ON is 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 (or EXPLAIN in PostgreSQL) and remember a SCAN can 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_id is None (NULL).

Run python -m pytest -v and push your completed fde-00-4 repository (including .github/workflows/pytest.yml) to GitHub.

5. Knowledge Check

  1. Why must foreign-key enforcement be enabled explicitly in SQLite, and how do you enable it on a connection?
  2. What is the difference between ON DELETE CASCADE and ON DELETE SET NULL, and what column requirement must ON DELETE SET NULL satisfy?
  3. Why must user-supplied values use SQL parameters rather than string interpolation or f-strings?
  4. What happens to earlier statements in a transaction when a later statement fails and the transaction rolls back?
  5. Why do indexes increase write overhead and storage usage?
  6. What is the difference between SEARCH and SCAN in EXPLAIN QUERY PLAN, and why is a SCAN not 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 CASCADE vs. ON DELETE SET NULL: ON DELETE CASCADE deletes child rows when a parent row is deleted, whereas ON DELETE SET NULL keeps child rows and sets the foreign key column to NULL (requiring the column to allow NULL).
  • 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. SEARCH vs. SCAN: SEARCH typically indicates an index lookup or direct key lookup, while SCAN reads rows sequentially across a table or index. A SCAN is 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 (users and tickets) created with primary keys, UNIQUE and CHECK constraints, and a foreign key using ON DELETE SET NULL.
  • Reusable connection function enables PRAGMA foreign_keys = ON and is closed cleanly in a finally block.
  • Parameterized queries (including get_tickets_by_assignee) and LEFT JOIN behavior implemented and tested.
  • Transaction rollback on a real constraint failure and EXPLAIN QUERY PLAN index check verified.
  • All pytest tests pass locally and in GitHub Actions, and the repository is committed to GitHub.
Practice assignment

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.

View reference repository ↗

Knowledge check

Test your understanding

  1. Why must foreign-key enforcement be enabled explicitly in SQLite, and how do you enable it on a connection?
  2. What is the difference between ON DELETE CASCADE and ON DELETE SET NULL, and what column requirement must ON DELETE SET NULL satisfy?
  3. Why must user-supplied values use SQL parameters rather than string interpolation or f-strings?
  4. What happens to earlier statements in a transaction when a later statement fails and the transaction rolls back?
  5. Why do indexes increase write overhead and storage usage?
  6. What is the difference between SEARCH and SCAN in EXPLAIN QUERY PLAN, and why is a SCAN not always inefficient?
Reveal self-review answers (attempt the questions first)
  1. Foreign-key enforcement: SQLite disables foreign keys by default for backwards compatibility, so each connection must run PRAGMA foreign_keys = ON;.
  2. ON DELETE CASCADE vs. ON DELETE SET NULL: ON DELETE CASCADE deletes child rows when a parent row is deleted, while ON DELETE SET NULL keeps child rows and sets the foreign key column to NULL (requiring the column to allow NULL).
  3. Parameterized queries: Bound parameters separate SQL structure from data values, preventing SQL injection and quoting bugs.
  4. Transaction rollback: Rolling back discards uncommitted changes from earlier statements in that transaction so partial updates do not persist.
  5. Index write overhead: Indexes use extra storage and must be updated on inserts, updates, and deletes touching indexed columns.
  6. SEARCH vs. SCAN: SEARCH uses an index or key lookup, whereas SCAN reads sequentially; a scan can be faster on small tables or queries returning most rows.
Not completed
Discussion & field notes

Questions or notes on this module?

Leave a note or question

Comments are held in a moderation queue and appear once approved. Your email will not be published.