00.7 SQL Basics with SQLite

FoundationsLesson 7 of 913,841 words10 parts
Module 00 · 0 of 9 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9

Almost every AI product you will build stores data in a database: support tickets, invoices, chat logs, eval results, token-usage and cost records, user accounts, the metadata that tells a RAG system which documents a user may see. The lingua franca of that storage is SQL — Structured Query Language — and the single most useful SQL skill for an applied AI engineer is being able to ask a table a question and get a correct answer. This lesson teaches SQL properly, from zero: the relational model, every core statement, joins, aggregation, indexes, transactions, and — just as important — how to use SQL safely from Python. Everything runs for real on SQLite, a complete database engine that ships inside Python's standard library, so every example in this lesson produces genuine output with no server, no account and no API key.

What you'll learn

  • What a relational database is (tables, rows, columns, keys, types) and why SQL is declarative — you describe the result, the engine finds the rows
  • SQLite versus PostgreSQL and MySQL, and when each matters on the AI path (including pgvector)
  • The full core of SQL: CREATE TABLE, INSERT, SELECT, WHERE, ORDER BY, LIMIT, UPDATE, DELETE, and every constraint (PRIMARY KEY, NOT NULL, UNIQUE, CHECK, foreign keys)
  • NULL and its three-valued logic — the source of most "my query returned the wrong rows" bugs
  • Aggregation and shaping: COUNT/SUM/AVG/MIN/MAX, GROUP BY, HAVING, CASE, COALESCE, subqueries, CTEs, window functions and views
  • Relationships: one-to-many and many-to-many, JOIN types, UNION, and anti-joins — including why joins duplicate rows
  • Design and integrity: normalization in plain language, indexes, EXPLAIN QUERY PLAN, transactions and ACID, backups and migrations
  • Using SQL from Python safely: parameterised queries, SQL injection, executemany, with conn: transactions, busy_timeout and WAL mode for "database is locked", pandas.read_sql, and what ORMs are for
  • A realistic AI-engineering table: an llm_calls usage log queried for cost, failures and latency
  • JSON inside SQL (json_extract, ->/->>), full-text search with FTS5, and why embeddings belong in vector stores instead
  • How to read and write good SQL: naming, formatting, SELECT *, and a common-mistakes table

What you don't need

  • Any database experience. If you've used a spreadsheet, you're most of the way there — a table is a spreadsheet with rules.
  • Any Python beyond running a script (Module 00 assumes a terminal and an editor; 00.1 covers setup). SQL itself needs no Python at all.
  • An API key, a server, Docker, or an account of any kind. SQLite is a library inside Python.

Setup

You need Python 3.11+ and nothing else — sqlite3 is part of the standard library. Check yours:

bash
python3 --version
python3 -c "import sqlite3; print(sqlite3.sqlite_version)"
text
Example output (illustrative — your exact output will differ):
Python 3.14.6
3.53.4

Optionally, the sqlite3 command-line shell (usually installed with Python or your OS) lets you type SQL interactively — we use it briefly in 2.4. Everything else in this lesson runs through Python.

The running example is a support-ticket database, tickets.db, built by a script printed in full in Part 2. Put it in your ai-path workspace next to your notes:

bash
mkdir -p ~/code/ai-path && cd ~/code/ai-path

No API key needed.


What you must be able to do after this lesson#

  • Explain tables, rows, columns and keys
  • Create a table with constraints and insert rows
  • Write SELECT queries with WHERE, ORDER BY and LIMIT
  • Explain why NULL breaks a comparison
  • Summarise data with GROUP BY and aggregate functions
  • Join two tables and explain why joins can duplicate rows
  • Run SQL from Python with parameterised queries

Why this matters for an AI engineer#

You'll hear... You'll understand it after...
"Pull last month's usage out of the llm_calls table." Part 3 and Part 5
"The eval results live in SQLite — can you query the failures?" Part 8, 10A.2
"Metadata for RAG is just rows with typed fields." Part 7, 05.8
"We put the vectors in pgvector inside Postgres." Part 9, 06.5
"Never concatenate user input into SQL." 8.2 Parameterised queries and SQL injection
"This query is slow — check the plan." 7.3 Indexes and EXPLAIN QUERY PLAN
"Wrap the refund and the ledger entry in one transaction." 7.4 Transactions
"Why did WHERE rating > 3 skip the unrated tickets?" 3.3 NULL and three-valued logic

Part 1: Why SQL, and what a relational database is#

1.1 The problem SQL solves#

Your ai-path app will accumulate rows of data: every support ticket, every API call, every eval run. At some point you need to ask questions of that data that no single file can answer:

  • "Which customers on the pro plan have open urgent tickets?"
  • "How many tickets did each agent resolve this month, and what was the average rating?"
  • "Show me the three most recent messages on ticket 17."
  • "Which tags appear on more than two tickets?"

You could answer these by loading everything into Python lists and filtering in a loop — and for twenty rows, you should; it's faster to write. But the moment the table has a hundred thousand rows, you want the database to do the filtering, because it is built for exactly this: storing rows on disk, indexing them, and answering queries without loading the whole table into memory.

SQL is the language for asking those questions. Two properties make it different from the Python you know:

  1. It is declarative. You describe what you want ("tickets that are open and urgent"), not how to find it ("loop through every row, check each field…"). The database's query planner — an optimizer inside SQLite/Postgres/MySQL — decides whether to scan the table row by row or use an index. You'll see its decisions in 7.3.
  2. It is set-based. One statement typically processes many rows at once and returns a table of results — even when you ask for one row, you get back a table with one row in it. This is why SQL feels different from Python's row-at-a-time loops, and why it's so fast at aggregation.

1.2 Tables, rows, columns, keys and types#

A relational database organises data into tables. Each table is a grid:

  • A column (also called a field or attribute) is one kind of fact about the thing the table describes — name, email, status. Every row has the same columns.
  • A row (also called a record or tuple) is one instance — one customer, one ticket.
  • A cell is the value at the intersection of one row and one column.
erDiagram
    customers ||--o{ tickets : "files"
    agents ||--o{ tickets : "handles"
    tickets ||--o{ messages : "contains"
    tickets ||--o{ ticket_tags : "has"
    tags ||--o{ ticket_tags : "labels"
    customers {
        int id PK
        text name
        text email UK
        text plan
        text created_at
    }
    agents {
        int id PK
        text name
        text team
        int manager_id FK
    }
    tickets {
        int id PK
        int customer_id FK
        int agent_id FK
        text subject
        text status
        text priority
        text channel
        text created_at
        text resolved_at
        int rating
    }
    messages {
        int id PK
        int ticket_id FK
        text author
        text body
        text created_at
    }
    tags {
        int id PK
        text name UK
    }
    ticket_tags {
        int ticket_id PK,FK
        int tag_id PK,FK
    }

Read the crow's feet: customers ||--o{ tickets means one customer can have many tickets, each ticket belongs to at most one customer. That single relationship — one-to-many — is the backbone of almost every schema you'll meet. tickets ||--o{ ticket_tags plus tags ||--o{ ticket_tags is the many-to-many pattern: a ticket can have many tags, a tag can label many tickets, and the ticket_tags table in the middle holds the pairs.

A few words you'll see constantly:

  • Primary key (PK): the column (or columns) that uniquely identifies each row. tickets.id — no two tickets share an id.
  • Foreign key (FK): a column that points at another table's primary key. tickets.customer_id holds a customers.id. This is what makes it relational — the database can enforce that you can't file a ticket for a customer who doesn't exist.
  • NULL: the marker for "no value here" — distinct from 0, '', or false. An unassigned ticket has agent_id = NULL, not agent_id = 0.
  • Schema: the blueprint of the database — the tables, columns, types and constraints. Changing it over time is called a migration (7.5).

1.3 SQL is declarative — meet the query planner#

When you write:

sql
SELECT subject FROM tickets WHERE status = 'open' ORDER BY created_at DESC;

you have said what you want. SQLite then chooses how: it could read all 20 rows and filter in memory, or — if an index on status exists — jump straight to the matching rows. The component that makes this choice is the query planner, and you can interrogate it with EXPLAIN QUERY PLAN, which you'll use in 7.3. The habit to build now: when a query feels slow, ask the planner why, don't guess.

1.4 SQLite vs PostgreSQL vs MySQL#

You will meet three databases constantly on the AI path. They all speak nearly identical SQL — the differences are in types, extensions and operations, not in the core statements this lesson teaches.

SQLite PostgreSQL MySQL
What it is A database engine as a library — no server, the whole DB is one file A full client–server database A full client–server database
Setup Nothing — import sqlite3 Install/run a server (or use a hosted one) Install/run a server (or managed)
Best for Prototypes, local tools, tests, small/medium apps, learning Production apps, serious data work Web apps, especially with PHP heritage
Types Flexible: any value can go in any column ("type affinity") Strict and rich: uuid, jsonb, arrays, ranges Strict-ish, good JSON support
Extensions JSON functions and FTS5 built in; sqlite-vec for vectors Huge ecosystem: pgvector, PostGIS, tsvector full-text Similar role to Postgres in web stacks
Concurrency One writer at a time Many concurrent readers and writers Many concurrent readers and writers
Where you'll meet it Everywhere in this lesson and Module 00 Production backends; pgvector for embeddings (06.5) Some companies' backends; same SQL skills transfer

1.5 Meet the running example: tickets.db#

Everything in this lesson queries one small database — a helpdesk's support tickets. It has seven tables (the diagram in 1.2 shows six of them; ticket_events is an audit log you'll meet in Part 9):

  • customers — who files tickets (name, email, plan: free/pro/enterprise)
  • agents — who answers them (name, team, manager — a self-reference)
  • tickets — the cases themselves (subject, status, priority, channel, timestamps, rating)
  • messages — the conversation inside each ticket
  • tags and ticket_tags — labels like bug, billing, outage (the many-to-many pair)
  • ticket_events — an audit trail whose payload column holds JSON

Twenty tickets, ten customers, four agents, forty messages — small enough to hold in your head, big enough that every query type produces interesting output. You'll build it yourself in Part 2.


Part 2: Creating and filling the database#

2.1 sqlite3 from Python: file vs :memory:#

Python's standard library includes sqlite3, a DB-API 2.0 driver — the same interface family every Python database driver follows. Two ways to connect:

python
import sqlite3

con = sqlite3.connect("tickets.db")   # a file on disk, next to your script
con = sqlite3.connect(":memory:")    # a throwaway database that vanishes on close
  • File databases (tickets.db) persist between runs — what real apps and this lesson use.
  • ":memory:" databases live only inside the connection. Perfect for tests and one-off experiments: nothing to clean up, nothing to commit to git. Many of the snippets later in this lesson use :memory: so they can't damage your tickets.db.

A Connection object manages the link to the database. You run SQL through cursors — objects that hold the result of one statement — though con.execute(...) is a shortcut that creates a cursor for you. You'll see the full API in Part 8; for now, the mental model is: connect → execute → fetch → close.

2.2 CREATE TABLE and the constraint vocabulary#

A table is created with CREATE TABLE, listing each column's name, type and optional constraints — rules the database enforces on every write:

sql
CREATE TABLE customers (
    id         INTEGER PRIMARY KEY,
    name       TEXT NOT NULL,
    email      TEXT NOT NULL UNIQUE,
    plan       TEXT NOT NULL DEFAULT 'free'
               CHECK (plan IN ('free', 'pro', 'enterprise')),
    created_at TEXT NOT NULL
);

Read it as: id is an integer primary key; name and email are required text (NOT NULL); email must be unique across all rows; plan defaults to 'free' if you don't supply it and may only be one of three values (CHECK); created_at is required.

The constraint vocabulary, complete:

Constraint Meaning Demo later
PRIMARY KEY Uniquely identifies each row; implies NOT NULL and UNIQUE 2.5
NOT NULL The column must have a value 2.5
UNIQUE No two rows may share this value (can span several columns) 2.5
DEFAULT x Value used when the INSERT omits the column 2.5
CHECK (expr) Row rejected unless the expression is true 2.5, 7.1
REFERENCES t (col) Foreign key: value must exist in table t's column (enforced only if PRAGMA foreign_keys = ON) 2.2
INTEGER PRIMARY KEY special case In SQLite, an INTEGER PRIMARY KEY column is the rowid — it auto-assigns 1, 2, 3… if you omit it 2.5

Types in SQLite are a promise, not a cage. SQLite has five storage classes — NULL, INTEGER, REAL (float), TEXT, BLOB (binary) — and column types are really affinities that nudge values toward a class. TEXT won't stop you storing 42; it just prefers text. Postgres is strict — integer rejects 'abc' outright. SQLite's flexibility is convenient early and a source of subtle bugs later (a column declared TEXT holding a number sorts differently). The discipline that transfers everywhere: declare the type you mean, and store that type.

2.3 Building tickets.db: the full script#

Here is the complete script that creates the running example. Save it as make_tickets_db.py in ~/code/ai-path/ and run python3 make_tickets_db.py. It deletes any existing tickets.db first, so it's safe to re-run — that property will matter in 7.5.

python
# make_tickets_db.py — create tickets.db, the running example for lesson 00.7.
# Run:  python3 make_tickets_db.py     (safe to re-run: rebuilds from scratch)
# Standard library only.
import os
import sqlite3

DB = "tickets.db"
if os.path.exists(DB):
    os.remove(DB)

con = sqlite3.connect(DB)
con.execute("PRAGMA foreign_keys = ON")   # enforce REFERENCES — set BEFORE any writes

con.executescript("""
CREATE TABLE customers (
    id         INTEGER PRIMARY KEY,
    name       TEXT NOT NULL,
    email      TEXT NOT NULL UNIQUE,
    plan       TEXT NOT NULL DEFAULT 'free'
               CHECK (plan IN ('free', 'pro', 'enterprise')),
    created_at TEXT NOT NULL              -- ISO 8601, e.g. '2026-01-05T14:15:00Z'
);

CREATE TABLE agents (
    id         INTEGER PRIMARY KEY,
    name       TEXT NOT NULL,
    team       TEXT,                       -- NULL allowed: Lena floats between teams
    email      TEXT,
    manager_id INTEGER REFERENCES agents (id)   -- self-reference: who they report to
);

CREATE TABLE tags (
    id   INTEGER PRIMARY KEY,
    name TEXT NOT NULL UNIQUE
);

CREATE TABLE tickets (
    id          INTEGER PRIMARY KEY,
    customer_id INTEGER NOT NULL REFERENCES customers (id),
    agent_id    INTEGER REFERENCES agents (id),   -- NULL while unassigned
    subject     TEXT NOT NULL,
    status      TEXT NOT NULL DEFAULT 'open'
                CHECK (status IN ('open', 'pending', 'resolved', 'closed')),
    priority    TEXT NOT NULL DEFAULT 'normal'
                CHECK (priority IN ('low', 'normal', 'high', 'urgent')),
    channel     TEXT NOT NULL DEFAULT 'email'
                CHECK (channel IN ('email', 'chat', 'phone')),
    created_at  TEXT NOT NULL,
    resolved_at TEXT,                      -- NULL until resolved
    rating      INTEGER CHECK (rating BETWEEN 1 AND 5)
);

CREATE TABLE ticket_tags (
    ticket_id INTEGER NOT NULL REFERENCES tickets (id),
    tag_id    INTEGER NOT NULL REFERENCES tags (id),
    PRIMARY KEY (ticket_id, tag_id)        -- composite key: the pair is unique
);

CREATE TABLE messages (
    id         INTEGER PRIMARY KEY,
    ticket_id  INTEGER NOT NULL REFERENCES tickets (id),
    author     TEXT NOT NULL CHECK (author IN ('customer', 'agent', 'system')),
    body       TEXT NOT NULL,
    created_at TEXT NOT NULL
);

CREATE TABLE ticket_events (
    id        INTEGER PRIMARY KEY,
    ticket_id INTEGER NOT NULL REFERENCES tickets (id),
    at        TEXT NOT NULL,
    kind      TEXT NOT NULL,               -- 'status_change' | 'assigned' | 'note'
    payload   TEXT NOT NULL                -- JSON text; see Part 9
);
""")

# The seed data, inserted with executemany + ? placeholders (Part 8 explains why).
con.executemany(
    "INSERT INTO customers (id, name, email, plan, created_at) VALUES (?, ?, ?, ?, ?)",
    [
        (1,  "Ada Lovelace",        "ada@example.com",      "pro",         "2025-11-02T10:00:00Z"),
        (2,  "Alan Turing",         "alan@example.com",     "free",        "2025-12-14T09:30:00Z"),
        (3,  "Grace Hopper",        "grace@example.com",    "enterprise",  "2026-01-05T14:15:00Z"),
        (4,  "Katherine Johnson",   "kat@example.com",      "pro",         "2026-01-20T11:45:00Z"),
        (5,  "Margaret Hamilton",   "margaret@example.com", "free",        "2026-02-03T08:20:00Z"),
        (6,  "Radia Perlman",       "radia@example.com",    "pro",         "2026-02-18T16:05:00Z"),
        (7,  "Dennis Ritchie",      "dennis@example.com",   "enterprise",  "2026-03-01T13:40:00Z"),
        (8,  "Barbara Liskov",      "barbara@example.com",  "free",        "2026-03-15T10:10:00Z"),
        (9,  "Ken Thompson",        "ken@example.com",      "pro",         "2026-04-02T09:00:00Z"),
        (10, "Frances Allen",       "frances@example.com",  "free",        "2026-04-20T15:55:00Z"),
    ],
)

# Managers first: Lena (4) reports to nobody, Tom (3) reports to Lena, and only then
# Priya (2, reports to Tom) and Sam (1, reports to Lena) — a row's manager must already exist.
con.executemany(
    "INSERT INTO agents (id, name, team, email, manager_id) VALUES (?, ?, ?, ?, ?)",
    [
        (4, "Lena Fischer", None,        "lena@helpdesk.example.com",   None),
        (3, "Tom Becker",   "technical", "tom@helpdesk.example.com",    4),
        (2, "Priya Nair",   "technical", "priya@helpdesk.example.com",  3),
        (1, "Sam Rivera",   "billing",   "sam@helpdesk.example.com",    4),
    ],
)

con.executemany(
    "INSERT INTO tags (id, name) VALUES (?, ?)",
    [(1, "billing"), (2, "bug"), (3, "feature-request"),
     (4, "outage"), (5, "how-to"), (6, "account")],
)

con.executemany(
    """INSERT INTO tickets
       (id, customer_id, agent_id, subject, status, priority, channel,
        created_at, resolved_at, rating) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
    [
        (1,  1,  2, "Cannot log in after password reset",           "resolved", "high",   "email", "2026-05-04T09:12:00Z", "2026-05-05T15:40:00Z", 5),
        (2,  2,  2, "Export to CSV times out on large reports",     "open",     "urgent", "chat",  "2026-05-06T11:03:00Z", None,                   None),
        (3,  3,  1, "Invoice shows wrong VAT amount",               "resolved", "normal", "email", "2026-05-07T08:44:00Z", "2026-05-08T10:20:00Z", 4),
        (4,  4,  3, "Webhook deliveries failing with 500",          "pending",  "high",   "email", "2026-05-08T14:26:00Z", None,                   None),
        (5,  5,  None,"How do I add a second admin user?",          "open",     "low",    "chat",  "2026-05-09T10:05:00Z", None,                   None),
        (6,  6,  2, "API rate limit hit during nightly sync",       "resolved", "high",   "email", "2026-05-10T22:31:00Z", "2026-05-12T09:15:00Z", 3),
        (7,  7,  3, "Dashboard charts render blank on Safari",      "closed",   "normal", "email", "2026-05-11T13:58:00Z", "2026-05-13T17:02:00Z", 4),
        (8,  8,  4, "Request: dark mode for the admin panel",       "open",     "low",    "email", "2026-05-12T09:37:00Z", None,                   None),
        (9,  9,  2, "Login loop on mobile app after update",        "resolved", "urgent", "chat",  "2026-05-13T18:22:00Z", "2026-05-14T08:50:00Z", 2),
        (10, 10, 1, "Refund for cancelled annual plan",             "resolved", "normal", "email", "2026-05-14T11:11:00Z", "2026-05-15T14:33:00Z", 5),
        (11, 1,  3, "Two-factor codes not arriving by SMS",         "pending",  "high",   "phone", "2026-05-15T16:47:00Z", None,                   None),
        (12, 3,  2, "Search returns stale results after edit",      "open",     "normal", "email", "2026-05-16T10:29:00Z", None,                   None),
        (13, 4,  None,"Bulk import fails with 'row 47: bad date'",  "open",     "high",   "email", "2026-05-17T15:03:00Z", None,                   None),
        (14, 6,  1, "Upgrade invoice missing purchase order field", "resolved", "low",    "email", "2026-05-18T12:36:00Z", "2026-05-19T11:08:00Z", 4),
        (15, 7,  4, "SSO login broken after IdP certificate rotation","open",   "urgent", "email", "2026-05-19T09:55:00Z", None,                   None),
        (16, 8,  2, "Export API documentation is outdated",         "closed",   "low",    "chat",  "2026-05-20T14:18:00Z", "2026-05-21T10:44:00Z", 3),
        (17, 9,  3, "Webhook signature validation failing",         "pending",  "high",   "email", "2026-05-21T08:27:00Z", None,                   None),
        (18, 10, 4, "Cannot delete workspace — 'in use' error",     "open",     "normal", "chat",  "2026-05-22T17:41:00Z", None,                   None),
        (19, 2,  1, "Double charge on May invoice",                 "resolved", "urgent", "phone", "2026-05-23T10:02:00Z", "2026-05-24T16:29:00Z", 5),
        (20, 5,  2, "Password reset email lands in spam folder",    "resolved", "normal", "email", "2026-05-24T13:50:00Z", "2026-05-25T09:12:00Z", 4),
    ],
)

con.executemany(
    "INSERT INTO ticket_tags (ticket_id, tag_id) VALUES (?, ?)",
    [(1, 6), (2, 4), (2, 2), (3, 1), (4, 2), (5, 5),
     (6, 4), (6, 2), (7, 2), (8, 3), (9, 6), (9, 2),
     (10, 1), (11, 6), (11, 4), (12, 2), (13, 5),
     (14, 1), (15, 6), (16, 5), (17, 2), (18, 5),
     (19, 1), (20, 6)],
)

con.executemany(
    """INSERT INTO messages (id, ticket_id, author, body, created_at)
       VALUES (?, ?, ?, ?, ?)""",
    [
        (1,  1, "customer", "I reset my password but still cannot log in. The reset email arrives but the link says expired.", "2026-05-04T09:15:00Z"),
        (2,  1, "agent",    "Sorry about that — the reset links expire after 15 minutes. Let's issue a fresh one now.", "2026-05-04T09:40:00Z"),
        (3,  1, "customer", "That worked, thanks!", "2026-05-04T10:02:00Z"),
        (4,  2, "customer", "The CSV export times out whenever the date range is more than a week. Small ranges are fine.", "2026-05-06T11:05:00Z"),
        (5,  2, "agent",    "Thanks for the detail. We are checking whether the timeout is in the report query or the file generation step.", "2026-05-06T12:30:00Z"),
        (6,  3, "customer", "Our May invoice shows 19% VAT but we are a UK company and should be charged 20%.", "2026-05-07T08:47:00Z"),
        (7,  3, "agent",    "You are right — the invoice was generated with the wrong rate. I have voided it and queued a corrected one.", "2026-05-07T09:20:00Z"),
        (8,  4, "customer", "Since Tuesday every webhook delivery returns HTTP 500. Our endpoint logs show the payload is fine.", "2026-05-08T14:30:00Z"),
        (9,  4, "agent",    "We can see elevated errors on our delivery workers. We are rolling back the deploy that went out Tuesday morning.", "2026-05-08T15:10:00Z"),
        (10, 5, "customer", "How do I add a second admin user? I only see the invite option for members.", "2026-05-09T10:08:00Z"),
        (11, 5, "agent",    "Admin invites are under Settings > Members > Invite, then choose the 'admin' role from the dropdown.", "2026-05-09T10:45:00Z"),
        (12, 6, "customer", "Our nightly sync hit the API rate limit at 02:00 and half the records did not sync.", "2026-05-10T22:35:00Z"),
        (13, 6, "agent",    "Pro plans include 600 requests/minute. I have bumped your workspace to the high-throughput tier for tonight.", "2026-05-11T08:15:00Z"),
        (14, 7, "customer", "All dashboard charts are blank in Safari but fine in Chrome. Started after the 2.4 release.", "2026-05-11T14:00:00Z"),
        (15, 7, "agent",    "This is a known rendering issue with Safari 17. A workaround is disabling the 'smooth charts' experiment in settings.", "2026-05-12T09:30:00Z"),
        (16, 9, "customer", "After updating the mobile app I am stuck in a login loop. Reinstalling did not help.", "2026-05-13T18:25:00Z"),
        (17, 9, "agent",    "The 4.2 update changed how session tokens are refreshed. Please log out fully, then log in once more.", "2026-05-13T19:05:00Z"),
        (18, 9, "customer", "Still looping. I cleared app data and it worked.", "2026-05-14T07:40:00Z"),
        (19, 10,"customer", "I cancelled the annual plan last week but was still charged for May. Please refund it.", "2026-05-14T11:15:00Z"),
        (20, 10,"agent",    "Confirmed — the cancellation processed after the billing run. A refund of $240.00 has been issued.", "2026-05-14T15:00:00Z"),
        (21, 11,"customer", "Two-factor codes stopped arriving by SMS around 4pm yesterday.", "2026-05-15T16:50:00Z"),
        (22, 11,"agent",    "Our SMS provider had an outage yesterday evening. Codes should be arriving again — please try now.", "2026-05-15T17:20:00Z"),
        (23, 12,"customer", "Search still shows the old title after I renamed a document an hour ago.", "2026-05-16T10:32:00Z"),
        (24, 12,"agent",    "The search index refreshes every 15 minutes. If it is still stale after that, we will rebuild the index for your workspace.", "2026-05-16T11:00:00Z"),
        (25, 13,"customer", "Bulk import fails at row 47 with 'bad date'. The file is a CSV export from our old system.", "2026-05-17T15:06:00Z"),
        (26, 13,"agent",    "Row 47 uses the format DD/MM/YYYY but the importer expects ISO dates. I can convert the file for you.", "2026-05-17T16:40:00Z"),
        (27, 14,"customer", "Our upgrade invoice is missing the purchase-order field our finance team requires.", "2026-05-18T12:40:00Z"),
        (28, 14,"agent",    "Invoices generated before May 15 did not include the PO field. I have added it to your account's invoice template.", "2026-05-18T13:15:00Z"),
        (29, 15,"customer", "SSO login broke this morning after we rotated the IdP signing certificate.", "2026-05-19T10:00:00Z"),
        (30, 15,"agent",    "Certificate rotation requires re-registering the new certificate thumbprint in your SSO settings. I can walk you through it.", "2026-05-19T11:30:00Z"),
        (31, 16,"customer", "The export API docs still describe v1 endpoints but we are on v2 now.", "2026-05-20T14:20:00Z"),
        (32, 16,"agent",    "Thanks for flagging — the docs page was two releases behind. It now covers v2 endpoints.", "2026-05-20T15:00:00Z"),
        (33, 17,"customer", "Webhook signature validation started failing after your key rotation on Monday.", "2026-05-21T08:30:00Z"),
        (34, 17,"agent",    "The rotation window overlapped with a deploy. We have re-synced your endpoint's signing secret.", "2026-05-21T09:45:00Z"),
        (35, 18,"customer", "I cannot delete the 'sandbox' workspace — the UI says it is still in use.", "2026-05-22T17:45:00Z"),
        (36, 18,"agent",    "A scheduled job inside that workspace is still running. I have paused it — try deleting again in a few minutes.", "2026-05-22T18:10:00Z"),
        (37, 19,"customer", "We were charged twice for May — once on the 1st and once on the 3rd.", "2026-05-23T10:05:00Z"),
        (38, 19,"agent",    "A retry in the payment gateway duplicated the charge. Both payments captured; I have refunded the duplicate $89.00.", "2026-05-23T14:00:00Z"),
        (39, 20,"customer", "Password reset emails keep landing in spam. Whitelisting did not help.", "2026-05-24T13:55:00Z"),
        (40, 20,"agent",    "Your domain's SPF record was missing our sender. I have sent updated DNS records to your admin.", "2026-05-24T15:30:00Z"),
    ],
)

con.executemany(
    """INSERT INTO ticket_events (id, ticket_id, at, kind, payload) VALUES (?, ?, ?, ?, ?)""",
    [
        (1,  1, "2026-05-04T09:12:00Z", "status_change", '{"from": "open", "to": "pending"}'),
        (2,  1, "2026-05-04T09:13:00Z", "assigned",      '{"agent_id": 2, "by": "auto-router"}'),
        (3,  1, "2026-05-05T15:40:00Z", "status_change", '{"from": "pending", "to": "resolved", "by": "agent:2"}'),
        (4,  2, "2026-05-06T11:04:00Z", "assigned",      '{"agent_id": 2, "by": "auto-router"}'),
        (5,  2, "2026-05-06T11:04:30Z", "status_change", '{"from": "open", "to": "pending"}'),
        (6,  3, "2026-05-07T09:20:00Z", "status_change", '{"from": "pending", "to": "resolved", "by": "agent:1"}'),
        (7,  4, "2026-05-08T15:00:00Z", "status_change", '{"from": "open", "to": "pending"}'),
        (8,  4, "2026-05-09T08:12:00Z", "note",          '{"text": "rolled back deploy 2026-05-06.2", "by": "agent:2"}'),
        (9,  9, "2026-05-13T19:05:00Z", "status_change", '{"from": "pending", "to": "resolved", "by": "agent:2"}'),
        (10, 10, "2026-05-14T15:00:00Z", "status_change", '{"from": "pending", "to": "resolved", "by": "agent:1"}'),
        (11, 11, "2026-05-15T17:25:00Z", "status_change", '{"from": "open", "to": "pending"}'),
        (12, 19, "2026-05-23T14:00:00Z", "status_change", '{"from": "pending", "to": "resolved", "by": "agent:1"}'),
    ],
)

con.commit()
for table in ("customers", "agents", "tickets", "tags",
              "ticket_tags", "messages", "ticket_events"):
    n = con.execute(f"SELECT COUNT(*) FROM {table}").fetchone()[0]
    print(f"{table}: {n} rows")
con.close()
print("Wrote", DB)
Output8 lines
customers: 10 rows
agents: 4 rows
tickets: 20 rows
tags: 6 rows
ticket_tags: 24 rows
messages: 40 rows
ticket_events: 12 rows
Wrote tickets.db

2.4 The sqlite3 command-line shell (optional)#

If your system has the sqlite3 CLI, you can type SQL interactively — handy for exploration:

bash
sqlite3 tickets.db
text
sqlite> .tables
agents   customers   messages   tags   ticket_events   ticket_tags   tickets

sqlite> .schema tickets
CREATE TABLE tickets (...);

sqlite> SELECT status, COUNT(*) AS n FROM tickets GROUP BY status;
closed   | 2
open     | 7
pending  | 3
resolved | 8

sqlite> .quit

Useful dot-commands: .tables, .schema [table], .headers on, .mode column, .quit. The CLI is a client — it reads the same file Python does. Everything the CLI can do, Python can do; we'll drive it from Python from here on so the examples are reproducible scripts.

Prefer a GUI? DB Browser for SQLite (sqlitebrowser.org) is the free, open-source, cross-platform visual client for exactly this file format — point it at tickets.db and you can browse and edit tables, run SQL and inspect the schema without typing commands. The division of labour: DB Browser for eyeballing data and sanity-checking a schema, the sqlite3 CLI for quick interactive queries, and Python for anything you want reproducible — which is why the rest of this lesson drives everything through scripts.

2.5 INSERT and its modern relatives#

INSERT adds rows. Columns may be omitted when they have a DEFAULT or are nullable:

sql
INSERT INTO tags (name) VALUES ('security');          -- id auto-assigns, thanks to INTEGER PRIMARY KEY
INSERT INTO tags (id, name) VALUES (8, 'performance');

Constraints reject bad data at write time — this is the database protecting you, and it's the same protection Postgres gives:

Output2 lines
sqlite> INSERT INTO tags (name) VALUES ('security');   -- second 'security' would violate UNIQUE
Error: UNIQUE constraint failed: tags.name

Two modern additions worth knowing (both need SQLite 3.24+/3.35+, so any Python from the last few years has them):

sql
-- INSERT ... RETURNING hands back the new row's values (3.35+)
INSERT INTO tickets (customer_id, subject, created_at)
VALUES (4, 'Test: RETURNING clause', '2026-05-25T09:00:00Z')
RETURNING id, status, priority;
-- → id=21, status='open', priority='normal'  (defaults filled in!)

-- UPSERT: insert or update on conflict (3.24+)
-- id 7 already exists as 'security' (auto-assigned by the first INSERT),
-- so ON CONFLICT fires DO UPDATE and the row comes back renamed:
INSERT INTO tags (id, name) VALUES (7, 'security-updates')
ON CONFLICT(id) DO UPDATE SET name = excluded.name
RETURNING id, name;
Output9 lines
id | status | priority
---+--------+---------
21 | open   | normal
(1 rows)

id | name
---+----------------
7  | security-updates
(1 rows)

Part 3: Reading data — SELECT#

SELECT is the workhorse: it reads rows and returns a result table. Every query in this part runs against your tickets.db. Outputs below are real, produced by Python's sqlite3 on SQLite 3.53.4 — your numbers will be identical because the data is fixed, provided tickets.db is a fresh build (re-run python3 make_tickets_db.py if you ran the mutation demos in 2.5).

3.1 Choosing columns, aliases and DISTINCT#

sql
SELECT * FROM tags ORDER BY id;
Output9 lines
id | name
---+----------------
1  | billing
2  | bug
3  | feature-request
4  | outage
5  | how-to
6  | account
(6 rows)

SELECT * grabs every column — fine for a six-column table you're eyeballing, a habit to unlearn for anything bigger (10.1). Name the columns you need:

sql
SELECT name, email, plan FROM customers ORDER BY id;
Output13 lines
name              | email                | plan
------------------+----------------------+-----------
Ada Lovelace      | ada@example.com      | pro
Alan Turing       | alan@example.com     | free
Grace Hopper      | grace@example.com    | enterprise
Katherine Johnson | kat@example.com      | pro
Margaret Hamilton | margaret@example.com | free
Radia Perlman     | radia@example.com    | pro
Dennis Ritchie    | dennis@example.com   | enterprise
Barbara Liskov    | barbara@example.com  | free
Ken Thompson      | ken@example.com      | pro
Frances Allen     | frances@example.com  | free
(10 rows)

Three more everyday tools:

  • AS aliases rename columns in the result (the table itself is unchanged): SELECT name AS customer, plan AS tier ...
  • DISTINCT collapses duplicate values:
sql
SELECT DISTINCT status FROM tickets ORDER BY status;
-- closed, open, pending, resolved  (4 rows, not 20)

SELECT DISTINCT customer_id, status FROM tickets ORDER BY customer_id, status LIMIT 8;
-- the (customer, status) pairs that actually occur
  • Expressions compute values on the fly: SELECT id, LENGTH(subject) AS title_len FROM tickets — you'll meet LENGTH, UPPER, SUBSTR, ROUND, date functions and more in 5.3.

3.2 WHERE: the filter vocabulary#

WHERE keeps only rows where the condition is true. The complete beginner set:

Operator Meaning Example
= != <> equal / not equal (!= and <> are synonyms) status = 'open'
< <= > >= comparisons rating >= 4, created_at < '2026-05-15'
AND OR NOT logic; AND binds tighter than OR — parenthesise! priority='urgent' OR (status='open' AND priority='high')
IN (...) value is one of a list status IN ('open','pending')
NOT IN (...) value is none of them plan NOT IN ('free')
BETWEEN a AND b inclusive range rating BETWEEN 1 AND 3
LIKE 'pat%' text pattern: % = any run of chars, _ = exactly one subject LIKE '%login%'
IS NULL / IS NOT NULL the only correct way to test NULL agent_id IS NULL

Real outputs on tickets.db:

sql
SELECT id, subject FROM tickets WHERE status = 'open' ORDER BY id;
-- 7 rows: ids 2, 5, 8, 12, 13, 15, 18

SELECT id, subject FROM tickets
WHERE status = 'open' AND priority = 'high' ORDER BY id;
-- 1 row: id 13 ("Bulk import fails with 'row 47: bad date'")

SELECT id, subject, priority FROM tickets
WHERE priority = 'urgent'
   OR (status = 'open' AND priority = 'high')
ORDER BY id;
-- 5 rows: the parentheses matter — without them 'open AND high' would bind wrong

SELECT id, subject, status FROM tickets
WHERE status IN ('open', 'pending') ORDER BY id;
-- 10 rows

SELECT id, subject FROM tickets WHERE rating BETWEEN 4 AND 5 ORDER BY id;
-- 7 rows (only resolved tickets have ratings)

SELECT id, subject FROM tickets WHERE subject LIKE '%login%' ORDER BY id;
-- ids 9 and 15 — LIKE is case-insensitive for ASCII by default

3.3 NULL and three-valued logic#

NULL means "unknown" or "not applicable" — and it behaves unlike any other value. Comparisons with NULL don't return false; they return a third truth value, UNKNOWN:

text
NULL = NULL        → UNKNOWN   (not true!)
NULL = 5           → UNKNOWN
5 = NULL           → UNKNOWN
NULL > 3           → UNKNOWN

In a WHERE clause, only true keeps a row — UNKNOWN and false both drop it. That's why the obvious-looking query silently misses rows:

sql
SELECT id, subject FROM tickets WHERE rating > 3 ORDER BY id;
-- 7 rows — every rated ticket scoring above 3
-- BUT the 10 tickets with rating = NULL are missing, not "failing" the test

The fix is always explicit: WHERE rating IS NOT NULL AND rating > 3, or restructure (WHERE rating IS NULL OR rating > 3 for "unrated or good"). The same trap bites NOT: WHERE NOT (rating > 3) still excludes NULLs, because NOT UNKNOWN is UNKNOWN.

Practical rules:

  • Test NULL with IS NULL / IS NOT NULL — never = NULL or != NULL (those always return UNKNOWN → zero rows).
  • COUNT(column) counts non-NULL values; COUNT(*) counts rows. COUNT(rating) on tickets returns 10, COUNT(*) returns 20.
  • NULL propagates through arithmetic and most functions: NULL + 1 is NULL, UPPER(NULL) is NULL.
  • COALESCE(a, b, ...) returns the first non-NULL argument — the standard "default value" tool: COALESCE(agent_id, 0), COALESCE(rating, -1). NULLIF(a, b) returns NULL when a = b (useful for turning a sentinel into NULL).
  • AND/OR truth table with NULL: false AND NULL → false; true OR NULL → true; everything else with a NULL → UNKNOWN. In practice: a NULL anywhere in an OR chain can only fail to save the row, never wrongly include it.

3.4 ORDER BY and LIMIT/OFFSET#

sql
SELECT id, status, priority, created_at FROM tickets
ORDER BY status, priority DESC, created_at
LIMIT 8;
Output10 lines
id | status  | priority | created_at
---+---------+----------+---------------------
7  | closed  | normal   | 2026-05-11T13:58:00Z
16 | closed  | low      | 2026-05-20T14:18:00Z
2  | open    | urgent   | 2026-05-06T11:03:00Z
15 | open    | urgent   | 2026-05-19T09:55:00Z
12 | open    | normal   | 2026-05-16T10:29:00Z
18 | open    | normal   | 2026-05-22T17:41:00Z
5  | open    | low      | 2026-05-09T10:05:00Z
8  | open    | low      | 2026-05-12T09:37:00Z
  • LIMIT 8 shows only the first 8 of the 20 rows.

  • Multiple sort keys apply left to right: status, then within each status by priority descending, then by creation time. DESC reverses one key; ASC is the default.

  • Text sorts alphabetically, not by meaning. priority DESC gave urgent, normal, low and (further down, not shown) high last — plain alphabetical order, urgent > normal > low > high, which is not the urgency order you want. To sort by business meaning, map the labels to numbers with CASE inside ORDER BY (5.3 shows CASE), or store a numeric rank column.

  • NULLs sort first in ascending order, last in descending (SQLite's default; Postgres puts NULLs last in ASC — a real portability trap worth remembering).

  • LIMIT n OFFSET m pages through results: LIMIT 5 OFFSET 10 skips 10 rows, returns 5. Fine for small data; for big tables, keyset pagination (WHERE id > :last_id ORDER BY id LIMIT 50) is what production APIs use — offset pagination slows down quadratically and skips/duplicates rows when data changes mid-scroll.


Part 4: Changing data — UPDATE, DELETE, DROP, and SQLite's types#

4.1 UPDATE and DELETE#

sql
UPDATE tickets SET status = 'closed' WHERE id = 16;             -- 1 row
UPDATE tickets SET priority = 'high'
WHERE status = 'open' AND priority = 'normal';                  -- 2 rows (ids 12, 18)
DELETE FROM ticket_events WHERE kind = 'note';                  -- removes audit noise

Three rules, all learned from real bugs:

  1. UPDATE/DELETE without WHERE hits every row. DELETE FROM tickets; empties the table. There is no undo — only your backup or transaction saves you (7.4). Always write the WHERE first, check it with a SELECT using the same predicate, then convert to UPDATE/DELETE.
  2. Check how many rows changed. Python's cursor exposes cursor.rowcount; in the CLI, SELECT changes() returns the count of the last DML statement. A "0 rows" update usually means your WHERE matched nothing — often a type mismatch (id = '7' vs id = 7 is fine in SQLite but not everywhere) or a NULL surprise.
  3. DELETE is permanent; "soft delete" is a column. Real systems rarely DELETE — they set deleted_at/archived_at and filter it out, keeping history for audits and recovery. Our resolved_at/rating NULLs are the same instinct: state is data.

4.2 DROP and the schema lifecycle#

sql
DROP TABLE scratch;          -- destroys the table AND its data, permanently
DROP TABLE IF EXISTS scratch; -- the safe spelling: no error if already gone
ALTER TABLE tickets RENAME COLUMN subject TO title;   -- evolve the schema
ALTER TABLE tickets ADD COLUMN sla_due TEXT;

DROP is the only statement that truly destroys data — DELETE removes rows, DROP removes the table itself. Treat it like rm -rf for your schema: fine on scratch tables, terrifying on real ones. Schema changes are migrations — versioned, reviewed scripts — covered conceptually in 7.5.

4.3 SQLite's flexible typing, dates, and STRICT#

SQLite stores five classes (NULL, INTEGER, REAL, TEXT, BLOB) and column declarations are affinities: TEXT prefers text but won't refuse 42. This is convenient — you can stash a JSON string, a date, or a number in one column — and dangerous, because comparisons across mismatched types behave differently on every engine — WHERE int_col = '42' happens to work in SQLite (affinity converts '42' to a number), but WHERE text_col = 42 or WHERE int_col = 'abc' is an error or a silent non-match depending on the engine. Three habits keep you safe on SQLite and Postgres:

  • Store dates/timestamps as ISO-8601 text ('2026-05-04T09:12:00Z') or as Unix-epoch integers. ISO text sorts and compares correctly as strings; that's why WHERE created_at >= '2026-05-15' returns exactly the right five tickets:
sql
SELECT id, subject, created_at FROM tickets
WHERE created_at >= '2026-05-15' AND created_at < '2026-05-20' ORDER BY created_at;
-- ids 11,12,13,14,15 — the May 15-19 window, boundaries inclusive/exclusive as written
  • Convert Python datetimes to text yourself. Passing a datetime object straight to execute() relied on a default adapter that Python 3.12 deprecated (it raises a DeprecationWarning, and may be removed later). Write when.isoformat(timespec="seconds") — for a timezone-aware UTC value that gives '2026-05-04T09:12:00+00:00' — and parse with datetime.fromisoformat(text) on the way out. Keep every stored timestamp in UTC so the text still sorts chronologically.

  • Declare new tables STRICT where you can. Since SQLite 3.37 (2021), a STRICT table gets real type enforcement like Postgres:

sql
CREATE TABLE strict_example (id INTEGER PRIMARY KEY, name TEXT, qty INTEGER) STRICT;
INSERT INTO strict_example (name, qty) VALUES ('widget', 'abc');
-- rejected: cannot store TEXT value in INTEGER column strict_example.qty (a normal table would accept it)

A STRICT table still coerces a value when the conversion loses nothing — 42 into a TEXT column is stored as '42', and '7' into an INTEGER column becomes 7 — and it rejects the rest. (Through Python's sqlite3 on SQLite 3.53.4 the failing insert raises sqlite3.IntegrityError; the exact message wording can vary by version.) Only the types INT, INTEGER, REAL, TEXT, BLOB and ANY are allowed in a STRICT table.


Part 5: Aggregation and shaping results#

This is where SQL stops being a filter and becomes an analyst. All outputs below are real, run on tickets.db.

5.1 The aggregate functions and GROUP BY#

The five workhorses: COUNT, SUM, AVG, MIN, MAX. Alone they collapse a whole table to one row:

sql
SELECT COUNT(*) AS n_tickets FROM tickets;                    -- 20
SELECT COUNT(rating) AS rated, COUNT(*) AS total FROM tickets; -- 10 | 20 (NULLs skipped!)
SELECT MIN(rating) AS worst, MAX(rating) AS best,
       ROUND(AVG(rating), 2) AS mean_rating, SUM(rating) AS points
FROM tickets WHERE rating IS NOT NULL;
-- worst=2, best=5, mean_rating=3.9, points=39

GROUP BY splits the table into buckets and aggregates within each:

sql
SELECT status, COUNT(*) AS n FROM tickets GROUP BY status ORDER BY status;
-- closed 2 | open 7 | pending 3 | resolved 8

SELECT status, COUNT(*) AS n, ROUND(AVG(rating), 2) AS avg_rating
FROM tickets GROUP BY status ORDER BY status;
-- closed 2 3.5 | open 7 NULL | pending 3 NULL | resolved 8 4.0

Note the NULL average for open/pending: those tickets are unrated, so AVG sees no values — three-valued logic again, this time in aggregates. Multi-column grouping works the same way: GROUP BY channel, status produced all nine channel×status combinations that occur.

The mental model: GROUP BY is itertools.groupby/pandas.groupby — declare the bucket keys, then each aggregate sees only that bucket's rows. Every non-aggregated column in the SELECT must be a grouping column (SQLite is lenient and picks an arbitrary row's value; Postgres rejects the query — write it the strict way so it works everywhere).

5.2 HAVING vs WHERE#

WHERE filters rows before grouping; HAVING filters groups after aggregating:

sql
-- Groups with at least 5 tickets:
SELECT status, COUNT(*) AS n FROM tickets
GROUP BY status HAVING COUNT(*) >= 5 ORDER BY status;
-- open 7 | resolved 8   (closed/pending dropped)

-- Agents with 2+ resolved tickets (WHERE first removes non-resolved rows):
SELECT agent_id, COUNT(*) AS resolved FROM tickets
WHERE status = 'resolved'
GROUP BY agent_id HAVING COUNT(*) >= 2 ORDER BY agent_id;
-- agent 1 → 4, agent 2 → 4

Rule of thumb: conditions on raw columns → WHERE; conditions on aggregates (COUNT(*), AVG(...)) → HAVING.

5.3 Expressions, functions and CASE#

SELECT isn't limited to stored columns — you can compute:

sql
SELECT id, subject, LENGTH(subject) AS title_len
FROM tickets ORDER BY title_len DESC LIMIT 3;
-- id 15 (47 chars), 14 (44), 13 (41)

SELECT id, UPPER(subject) AS shout, SUBSTR(subject, 1, 20) AS preview
FROM tickets WHERE id <= 3 ORDER BY id;

SELECT id, created_at, DATE(created_at) AS day,
       strftime('%w', created_at) AS dow          -- 0=Sunday..6=Saturday
FROM tickets WHERE id <= 5 ORDER BY id;

CASE is the if/elif/else of SQL — the standard way to turn codes into labels:

sql
SELECT id, subject,
  CASE WHEN priority = 'urgent' THEN '!!'
       WHEN priority = 'high'   THEN '!'
       ELSE '' END AS flag
FROM tickets ORDER BY id LIMIT 8;
Output11 lines
id | subject                                  | flag
---+------------------------------------------+-----
1  | Cannot log in after password reset       | !
2  | Export to CSV times out on large reports | !!
3  | Invoice shows wrong VAT amount           |
4  | Webhook deliveries failing with 500      | !
5  | How do I add a second admin user?        |
6  | API rate limit hit during nightly sync   | !
7  | Dashboard charts render blank on Safari  |
8  | Request: dark mode for the admin panel   |
(8 rows)

The function library is large; the ones you'll actually use: string — LENGTH, LOWER, UPPER, SUBSTR, TRIM, REPLACE, INSTR, || (concat); numeric — ROUND, ABS, MIN/MAX (scalar form with two args); date — DATE, DATETIME, strftime, julianday, unixepoch; NULL — COALESCE, NULLIF, IFNULL; JSON — Part 9. For exhaustive lists, sqlite.org/lang_corefunc.html is the reference — bookmark it.

5.4 Subqueries: queries inside queries#

A subquery is a SELECT nested inside another statement. Three shapes:

sql
-- Scalar: returns one value, usable anywhere an expression is
SELECT id, subject FROM tickets
WHERE rating = (SELECT MAX(rating) FROM tickets) ORDER BY id;
-- ids 1, 10, 19 (rating = 5)

-- IN: "whose id appears in this set"
SELECT id, name FROM agents
WHERE id IN (SELECT agent_id FROM tickets
             WHERE status = 'open' AND agent_id IS NOT NULL) ORDER BY id;
-- Priya Nair, Lena Fischer

-- Correlated: the inner query references the outer row — runs once per row
SELECT t.id, t.subject,
       (SELECT COUNT(*) FROM messages m WHERE m.ticket_id = t.id) AS n_messages
FROM tickets t ORDER BY n_messages DESC, t.id LIMIT 5;
-- tickets 1 and 9 lead with 3 messages each

The correlated form is powerful but easy to make slow — the inner query re-runs per outer row. At 20 rows it's instant; at 20 million it's a performance incident. When a correlated subquery becomes the bottleneck, rewrite it as a JOIN or a window function (5.6).

5.5 CTEs: WITH for readable multi-step queries#

A CTE (common table expression) names an intermediate result so you can build a query in steps:

sql
WITH open_tickets AS (
    SELECT id, subject, customer_id FROM tickets WHERE status = 'open'
)
SELECT c.name, t.subject
FROM open_tickets t JOIN customers c ON c.id = t.customer_id
ORDER BY c.name;
-- 7 rows: each open ticket with its customer's name

CTEs chain and recurse (WITH RECURSIVE does tree walks — org charts, bill-of-materials). They're the readability tool senior engineers reach for first: name each step, then join the steps. Almost every complex query in production SQL starts life as a CTE.

5.6 Window functions: aggregate without losing rows#

Window functions compute over a sliding view of rows without collapsing them — unlike GROUP BY, every row survives. Syntax: fn(args) OVER (PARTITION BY ... ORDER BY ...).

sql
-- Latest message per ticket, ranked inside each ticket's partition
SELECT ticket_id, author, body, created_at,
    ROW_NUMBER() OVER (PARTITION BY ticket_id ORDER BY created_at DESC) AS rn
FROM messages WHERE ticket_id IN (1, 2) ORDER BY ticket_id, rn;
-- rn=1 is the newest message in each ticket

Filter to rn = 1 in an outer query (or a CTE) and you have "the latest X per group" — the query that otherwise needs a correlated subquery or a self-join:

sql
SELECT m.ticket_id, m.author, m.body, m.created_at
FROM (
    SELECT *, ROW_NUMBER() OVER
        (PARTITION BY ticket_id ORDER BY created_at DESC) AS rn
    FROM messages
) m
WHERE m.rn = 1 ORDER BY m.ticket_id;
-- 19 rows: the final message on every ticket that has messages
-- (ticket 8 has none — see the LEFT JOIN lesson in Part 6)

Other workhorses: RANK()/DENSE_RANK() (ties share rank), LAG()/LEAD() (previous/next row's value — deltas and gaps), running totals via SUM(x) OVER (ORDER BY ...), and COUNT(*) OVER () for "total rows" alongside per-group counts. Window functions exist in SQLite since 3.25, Postgres forever — one of the best SQL investments you can make.

5.7 Views: a saved query with a name#

A view is a SELECT stored under a name; querying the view runs the saved query. It stores no data of its own, so it is always current. Views are how teams hide a three-table join behind one friendly table name — for example, the table an analyst or a dashboard queries:

sql
CREATE VIEW ticket_overview AS
SELECT t.id, t.subject, t.status, c.name AS customer,
       COALESCE(a.name, '(unassigned)') AS agent
FROM tickets t
JOIN customers c ON c.id = t.customer_id
LEFT JOIN agents a ON a.id = t.agent_id;

SELECT id, customer, agent FROM ticket_overview WHERE status = 'open' ORDER BY id LIMIT 3;
-- 2 | Alan Turing       | Priya Nair
-- 5 | Margaret Hamilton | (unassigned)
-- 8 | Barbara Liskov    | Lena Fischer

DROP VIEW ticket_overview;   -- tidy up: this lesson's later outputs do not need the view

A view is not a faster query (SQLite runs the underlying SELECT each time) and it is not a copy; the materialized views of Postgres, which do store results, have no SQLite equivalent. Use a view for naming and reuse; use an index for speed (7.3).


Part 6: Relationships and JOINs#

Tables are only half the model; the other half is how they relate. tickets.customer_id doesn't contain the customer — it points to customers.id. A JOIN stitches tables back together at query time.

6.1 The four JOIN shapes#

erDiagram
    tickets ||--o{ messages : "has many"
    customers ||--o{ tickets : "files"
    tickets }o--o| agents : "assigned to (nullable)"

For "tickets joined to their customers", the options:

JOIN Rows returned
INNER JOIN Only pairs where the match exists both ways — the default
LEFT JOIN (a.k.a. LEFT OUTER JOIN) Every row of the left table, with NULLs where no right-side match
RIGHT JOIN Mirror of LEFT (SQLite ≥ 3.39, 2022)
FULL OUTER JOIN Both sides' unmatched rows (SQLite ≥ 3.39)
Comma / CROSS JOIN Every combination — almost never what you want alone
sql
-- INNER: tickets that HAVE a customer (all 20 here)
SELECT t.id, c.name AS customer, t.subject
FROM tickets t JOIN customers c ON c.id = t.customer_id
WHERE t.id <= 5 ORDER BY t.id;

-- LEFT: every ticket, agent name or NULL when unassigned
SELECT t.id, t.subject, COALESCE(a.name, '(unassigned)') AS agent
FROM tickets t LEFT JOIN agents a ON a.id = t.agent_id
WHERE t.agent_id IS NULL ORDER BY t.id;
-- ids 5 and 13 — the two tickets nobody has picked up

The ON clause states the relationship; WHERE then filters the joined result. Mixing them up is the classic beginner error: WHERE on the right table's columns silently converts a LEFT JOIN into an INNER JOIN (NULLs fail the comparison). If your LEFT JOIN "lost" rows, check for a stray WHERE right_table.col = ....

6.2 Many-to-many joins and the duplication trap#

ticket_tags exists precisely because tickets↔tags is many-to-many. Joining through it:

sql
SELECT t.id AS ticket, tg.name AS tag
FROM tickets t
JOIN ticket_tags tt ON tt.ticket_id = t.id
JOIN tags tg ON tg.id = tt.tag_id
WHERE t.id IN (2, 9) ORDER BY t.id, tg.name;
-- ticket 2: bug, outage | ticket 9: account, bug

Joins duplicate rows — that's their job. Ticket 2 appears twice because it has two tags. This is correct and dangerous:

sql
SELECT COUNT(*) AS joined_rows
FROM tickets t JOIN ticket_tags tt ON tt.ticket_id = t.id;
-- 24 — not 20!  (24 tag assignments across 20 tickets)

SELECT COUNT(DISTINCT t.id) AS distinct_tickets
FROM tickets t JOIN ticket_tags tt ON tt.ticket_id = t.id;
-- 20 — the count you probably wanted

Same trap with aggregates: SUM(t.rating) after a join counts a ticket once per matching tag. Rules: count entities with COUNT(DISTINCT id), or aggregate on the "one" side before joining, or join to a pre-aggregated subquery/CTE. Whenever a JOIN meets COUNT/SUM, pause and ask "can rows be duplicated?"

6.3 Self-joins, UNION, and anti-joins#

A self-join joins a table to itself — here, agents to their managers:

sql
SELECT a.name AS agent, COALESCE(m.name, '(top of chain)') AS manager
FROM agents a LEFT JOIN agents m ON m.id = a.manager_id ORDER BY a.name;
-- Lena → top | Priya → Tom | Sam → Lena | Tom → Lena

UNION stacks two result sets vertically, removing duplicates; UNION ALL keeps them (and is faster — prefer it unless you need dedup):

sql
SELECT name AS who FROM customers WHERE id <= 2
UNION SELECT name FROM agents WHERE id <= 2 ORDER BY who;
-- Ada Lovelace, Alan Turing, Priya Nair, Sam Rivera

Anti-joins find rows with no match — "tickets with no messages", "customers who never filed a ticket". Two equivalent spellings:

sql
SELECT t.id, t.subject FROM tickets t
WHERE NOT EXISTS (SELECT 1 FROM messages m WHERE m.ticket_id = t.id);
-- id 8 only

SELECT t.id, t.subject FROM tickets t
LEFT JOIN messages m ON m.ticket_id = t.id
WHERE m.id IS NULL;
-- same answer — the LEFT JOIN + IS NULL idiom

EXISTS/NOT EXISTS reads best for "has/hasn't any"; LEFT JOIN ... IS NULL is the same thing wearing a join. Both beat NOT IN (subquery) — which has a notorious NULL trap: if the subquery can return NULL, NOT IN returns nothing at all. Prefer NOT EXISTS.


Part 7: Design and integrity#

Deep-dive

Parts 3–6 taught you to use tables. This part is about designing them well — the difference between a database that stays correct at scale and one that slowly rots.

7.1 Constraints, recapped as integrity#

Every constraint from 2.2 is a promise the database keeps for you. The failures, all real:

Output4 lines
UNIQUE constraint failed: customers.email        -- duplicate email
NOT NULL constraint failed: customers.email      -- NULL where required
FOREIGN KEY constraint failed                    -- ticket for customer 999
CHECK constraint failed: rating BETWEEN 1 AND 5  -- rating = 9

(CHECK passes on NULL — rating NULL is allowed because "no rating yet" is legitimate. That's why BETWEEN constraints don't accidentally demand a value.) The engineering lesson: push invariants into the schema — "status is one of four values", "rating is 1–5", "email is unique" — so no bug, script or tired human can write a row that violates them. Application code then only handles business rules the schema can't express.

7.2 Normalization in plain language#

Normalization is the discipline of storing each fact exactly once. The anti-pattern is the wide row — one table cramming everything together:

text
BAD:  tickets(id, customer_name, customer_email, customer_plan,
              agent_name, subject, status, tag1, tag2, tag3)

This breaks immediately: a customer's email changes → update 40 ticket rows; a ticket needs a 4th tag → new column; "which plan do most ticket-filers have?" → scan and dedupe text. The normalized design — our tickets.db — splits facts into tables and reconnects them with keys:

  • 1NF (first normal form): each column holds one atomic value; no repeating groups, no comma-separated lists inside a cell. tag1/tag2/tag3 violates it; ticket_tags satisfies it.
  • 2NF: every non-key column depends on the whole primary key. With composite keys like (ticket_id, tag_id), a column describing only ticket_id belongs in tickets, not the join table.
  • 3NF: no transitive dependencies — customer_plan derived from customer_id belongs in customers, not copied onto every ticket.

When to denormalize on purpose: read-heavy paths where a join per query is too expensive (a customers.name copied onto a reporting table), or where the "one fact" genuinely has two valid versions (a snapshot: "the plan at the time of the ticket" — history legitimately differs from current state). Denormalization is a trade: write complexity and drift risk for read speed. The glossary already covers the RAG flavour of this idea — 05.8 denormalises chunk metadata because vector stores can't join; in a real relational database you can join, so you normalize first and denormalize only with a reason.

7.3 Indexes and EXPLAIN QUERY PLAN#

An index is a sorted lookup structure (a B-tree) that lets the engine find rows without scanning the whole table — the difference between looking up a name in a book's index versus reading every page.

sql
CREATE INDEX idx_tickets_customer ON tickets (customer_id);
CREATE INDEX idx_tickets_created  ON tickets (created_at);

Now ask the query planner what it would do (abbreviated to the detail column; a real EXPLAIN QUERY PLAN result has four columns):

Example output · illustrative7 lines
EXPLAIN QUERY PLAN SELECT * FROM tickets WHERE customer_id = 3;
-- before:  SCAN tickets
-- after:   SEARCH tickets USING INDEX idx_tickets_customer (customer_id=?)

EXPLAIN QUERY PLAN SELECT * FROM tickets ORDER BY created_at DESC LIMIT 5;
-- before:  SCAN tickets + USE TEMP B-TREE FOR ORDER BY
-- after:   SCAN tickets USING INDEX idx_tickets_created   (reads in order, no sort)

Reading plans: SCAN = read every row (fine for tiny tables); SEARCH ... USING INDEX = jumped to the matches; USE TEMP B-TREE = had to sort in memory. The index trade-off: every INSERT/UPDATE/DELETE must also update every index on the table — indexes speed reads and slow writes. Rule of thumb: index columns you filter/join/sort on often; don't index everything "just in case". Primary keys and UNIQUE constraints create automatic indexes (sqlite_autoindex_*).

7.4 Transactions, ACID and Python's with conn:#

A transaction is a bundle of statements that succeed or fail together. The classic example — a bank transfer must debit one account and credit another, never one without the other:

sql
BEGIN;
UPDATE accounts SET balance = balance - 30 WHERE id = 1;
UPDATE accounts SET balance = balance + 30 WHERE id = 2;
COMMIT;    -- or ROLLBACK to undo everything since BEGIN

ACID in plain words: Atomic (all-or-nothing), Consistent (constraints hold at commit), Isolated (concurrent transactions don't see each other's half-done work), Durable (committed data survives a crash — SQLite's journal file is the mechanism). You get all four by default; you rarely configure them.

Python maps this beautifully — with con: is the transaction. Here is a complete, self-contained demo on a throwaway in-memory database (it never touches tickets.db); save it as transfer_demo.py and run it:

python
# transfer_demo.py — `with con:` commits on success and rolls back on an exception.
import sqlite3

con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE accounts (id INTEGER PRIMARY KEY, "
            "balance INTEGER NOT NULL CHECK (balance >= 0))")
con.executemany("INSERT INTO accounts VALUES (?, ?)", [(1, 100), (2, 50)])
con.commit()


def transfer(src: int, dst: int, amount: int) -> None:
    with con:                                   # BEGIN happens implicitly on the first UPDATE
        con.execute("UPDATE accounts SET balance = balance - ? WHERE id = ?", (amount, src))
        found = con.execute("SELECT COUNT(*) FROM accounts WHERE id = ?", (dst,)).fetchone()[0]
        if found == 0:
            raise ValueError(f"no such account: {dst}")   # -> ROLLBACK of the debit too
        con.execute("UPDATE accounts SET balance = balance + ? WHERE id = ?", (amount, dst))
    # no exception -> COMMIT. Either way the connection stays OPEN.


try:
    transfer(1, 99, 30)                         # destination does not exist
except ValueError as err:
    print("failed:", err)
print("after failed transfer:", con.execute("SELECT id, balance FROM accounts ORDER BY id").fetchall())

transfer(1, 2, 30)                              # a valid transfer
print("after good transfer:  ", con.execute("SELECT id, balance FROM accounts ORDER BY id").fetchall())
print("connection still usable:", con.execute("SELECT 1").fetchone()[0] == 1)
con.close()                                     # `with con:` never closes it - you do
Output4 lines
failed: no such account: 99
after failed transfer: [(1, 100), (2, 50)]
after good transfer:   [(1, 70), (2, 80)]
connection still usable: True

The debit of account 1 was rolled back together with the failed transfer, so both balances were unchanged. with con: does not close the connection (a common surprise); call con.close() yourself, or wrap the connection in contextlib.closing. The CHECK (balance >= 0) constraint is a second safety net: an overdraft would raise sqlite3.IntegrityError inside the with block and roll back the same way.

7.5 Migrations and backups#

  • Migrations are versioned schema changes — ALTER TABLE ... ADD COLUMN, CREATE INDEX, data backfills — applied in order and recorded in a table (e.g. schema_migrations). ORMs like SQLAlchemy/Alembic generate and track them; hand-rolled projects keep numbered .sql files. The discipline: never edit a CREATE TABLE that already ran somewhere — write the next migration instead. For tickets.db, re-running make_tickets_db.py is the honest "migration" — a rebuildable demo database needs none.
  • Backups for SQLite are trivially safe: copy the file while no writer is active, or use the online backup API — source_con.backup(dest_con) in Python, where dest_con is a second sqlite3.connect("backup.db") connection, or the CLI's .backup file.db. Never copy a live WAL-mode database file-by-file mid-write; the backup API handles the locking correctly. Postgres backups are pg_dump/PITR — same concept, more machinery.

Part 8: Using SQL from Python safely#

Everything so far ran through a helper. This part is the production version: how real Python code talks to SQLite — and the one mistake that tops every "SQL injection" hall of fame.

8.1 Connecting, cursors, row_factory, fetching#

python
import sqlite3

con = sqlite3.connect("tickets.db")
con.row_factory = sqlite3.Row        # rows behave like dicts: row["name"], row.keys()
con.execute("PRAGMA foreign_keys = ON")   # FIRST, before any DML

cur = con.cursor()
cur.execute("SELECT id, name, plan FROM customers WHERE plan = ? ORDER BY id LIMIT 3",
            ("pro",))
for row in cur.fetchall():
    print(dict(row))
# {'id': 1, 'name': 'Ada Lovelace', 'plan': 'pro'} ...

# con.execute() is a shortcut returning a cursor:
for row in con.execute(
    "SELECT status, COUNT(*) AS n FROM tickets GROUP BY status ORDER BY status"):
    print(row["status"], "->", row["n"])        # column access by name!

print(con.execute("SELECT COUNT(*) FROM tickets").fetchone()[0])   # 20
print(dict(con.execute("SELECT * FROM agents WHERE id = 2").fetchone()))

con.close()
Output9 lines
{'id': 1, 'name': 'Ada Lovelace', 'plan': 'pro'}
{'id': 4, 'name': 'Katherine Johnson', 'plan': 'pro'}
{'id': 6, 'name': 'Radia Perlman', 'plan': 'pro'}
closed -> 2
open -> 7
pending -> 3
resolved -> 8
20
{'id': 2, 'name': 'Priya Nair', 'team': 'technical', 'email': 'priya@helpdesk.example.com', 'manager_id': 3}

The API surface, complete enough for daily work: con.execute(sql, params) → cursor; cursor.fetchone() (one row or None), .fetchall() (list), .fetchmany(n); cursor.rowcount after DML; iteration over the cursor streams rows lazily (memory-friendly on big results); con.commit(), con.rollback(), con.close(); con.in_transaction tells you whether a transaction is open.

8.2 Parameterised queries and SQL injection#

Never build SQL by interpolating values into the string. The wrong way:

python
import sqlite3

con = sqlite3.connect("tickets.db")
con.row_factory = sqlite3.Row            # so dict(row) works


def lookup_ticket_unsafe(ticket_id_text: str):
    sql = f"SELECT id, subject, status FROM tickets WHERE id = {ticket_id_text}"
    return con.execute(sql).fetchall()


print("normal call:", [dict(r) for r in lookup_ticket_unsafe("7")])      # fine...
injected = lookup_ticket_unsafe("7 OR 1=1")                              # ...until user input rewrites your WHERE clause
print("injected call returned", len(injected), "rows — the WHERE clause was rewritten")
Output2 lines
normal call: [{'id': 7, 'subject': 'Dashboard charts render blank on Safari', 'status': 'closed'}]
injected call returned 20 rows — the WHERE clause was rewritten

"7 OR 1=1" turned WHERE id = 7 into WHERE id = 7 OR 1=1 — a tautology returning every row. On a login form it's admin' OR '1'='1; on an orders table it's '; DROP TABLE orders; --. (Python's sqlite3 execute() refuses a second statement — it raises ProgrammingError: You can only execute one statement at a time — which blocks that particular stacked attack, but not the tautology above, nor executescript(), nor other drivers and languages that allow stacked statements. Never rely on the driver to save you.) The fix is parameters — values travel separately from the SQL text, so they can only ever be values:

python
def lookup_ticket(ticket_id: int):
    return con.execute(
        "SELECT id, subject, status FROM tickets WHERE id = ?",
        (ticket_id,),
    ).fetchall()

print([dict(r) for r in lookup_ticket(7)])   # the ticket: [{'id': 7, ...}]
print(lookup_ticket("7 OR 1=1"))             # [] — compared as a *value*, matches nothing, no error

Two placeholder styles: ? positional (a tuple of params) and :name named (a dict) — the named form is more readable for many params:

python
con.execute(
    """SELECT c.name, COUNT(*) AS n
       FROM customers c JOIN tickets t ON t.customer_id = c.id
       WHERE c.plan = :plan AND t.status = :status
       GROUP BY c.name ORDER BY n DESC, c.name LIMIT 3""",
    {"plan": "pro", "status": "resolved"},
).fetchall()
# [{'name': 'Radia Perlman', 'n': 2}, {'name': 'Ada Lovelace', 'n': 1},
#  {'name': 'Ken Thompson', 'n': 1}]   (as dicts; ties broken by name)

8.3 Transactions from Python, executemany, and the pragma trap#

Bulk inserts use executemany — one statement, many parameter sets:

python
con.executemany(
    "INSERT INTO tickets (customer_id, subject, created_at) VALUES (?, ?, ?)",
    [(4, "Bulk item A", "2026-05-25T09:00:00Z"),
     (4, "Bulk item B", "2026-05-25T09:01:00Z")],
)
con.commit()

Transactions in Python — three levels, pick by need:

python
# 1. Manual, for scripts:
con.execute("BEGIN")
# ... work ...
con.commit()          # or con.rollback()

# 2. `with con:` — commits on success, rolls back on exception, stays open:
with con:
    con.execute("UPDATE tickets SET status='closed' WHERE id = 16")

# 3. autocommit=True (Python 3.12+) — each statement commits itself;
#    use explicit BEGIN when you need a multi-statement transaction.

The pragma trap, demonstrated live (Python 3.14, SQLite 3.53.4):

python
import sqlite3

con = sqlite3.connect("tickets.db")      # a fresh build (see the warning above about mutations)
con.execute("INSERT INTO agents (name, team) VALUES ('Temp', 'temp')")
print(con.in_transaction)                     # True — implicit BEGIN happened
con.execute("PRAGMA foreign_keys = ON")       # silently does NOTHING inside a txn
print(con.execute("PRAGMA foreign_keys").fetchone())   # (0,) — still off!
con.rollback()                                # undo the temp agent
con.execute("PRAGMA foreign_keys = ON")       # now it works
print(con.execute("PRAGMA foreign_keys").fetchone())   # (1,)
con.close()
Output3 lines
True
(0,)
(1,)

The rule that prevents a whole class of "foreign keys not working" bugs: set pragmas immediately after connect(), before any other statement. Same family of gotcha: busy_timeout and foreign_keys are per-connection settings (the journal mode is the one that persists in the file — 8.5) — set them in one connect() helper every script shares.

8.4 pandas, ORMs, and where each fits#

  • pandas read_sql: pd.read_sql("SELECT ...", con) accepts a sqlite3 connection directly and returns a DataFrame — the standard way to move query results into analysis (01B.11 covers pandas properly). For big tables pass chunksize= to stream. Write-back (to_sql) exists but is for prototyping — real writes belong in parameterised SQL.
  • ORMs (SQLAlchemy, SQLModel, Django ORM, Peewee): map tables to Python classes so you write session.query(Ticket).filter_by(status="open") instead of SQL. They earn their keep on large schemas and team codebases — migrations, relationships, dialect portability. They are not magic: the ORM still emits SQL, and "ORM-generated N+1 queries" is a classic production slowdown. (The session.query(...) style shown is SQLAlchemy 1.x; 2.x writes select(Ticket).where(Ticket.status == "open") executed via session.execute(...) — same idea, different spelling.) Learn raw SQL first (this lesson); learn an ORM when a project demands it. Some teams standardise on Django's ORM or SQLModel, so you may meet them on the job — but the SQL underneath is what transfers.
  • Query builders (SQLAlchemy Core, sqlite-utils, dataset): middle ground — Pythonic construction that still emits real SQL you can inspect. Good for dynamic queries.

8.5 Concurrency settings: busy_timeout, WAL and BEGIN IMMEDIATE#

SQLite lets many connections read, but only one write at a time (1.4). A second writer that arrives while the first is still working does not fail at once: it waits for the lock for a busy timeout, and only then raises sqlite3.OperationalError: database is locked. Python's sqlite3.connect() waits 5 seconds by default (timeout=5.0); PRAGMA busy_timeout = <milliseconds> sets the same thing in SQL. A web service or an eval runner with several threads or processes writing to one file is where you meet this error first.

Two settings cover most real cases:

  • WAL mode — PRAGMA journal_mode = WAL switches from SQLite's default rollback journal to a write-ahead log: changes are appended to a side file (tickets.db-wal) and merged into the main file later. The practical effect (from the SQLite documentation, sqlite.org/wal.html) is that readers no longer block the writer and the writer no longer blocks readers; it is still one writer at a time. Unlike most pragmas, the WAL setting is stored in the database file, so you set it once and every later connection uses it. Do not put a WAL database on a network file share, and remember that a WAL database is now three files (.db, -wal, -shm) — copy it with the backup API (7.5), not with cp while it is in use.
  • BEGIN IMMEDIATE — a normal BEGIN is deferred: it takes no lock until the first statement. If a transaction first reads and then writes, another writer can slip in between and your write then fails with database is locked straight away, even though a busy timeout is set (the data you read is already out of date, so waiting would not help). BEGIN IMMEDIATE takes the write lock up front, so you wait once, at the start, and the rest of the transaction cannot be interrupted.

Here is the whole story in one runnable file. It builds a throwaway database in a temporary folder (it never touches tickets.db), shows WAL being stored in the file, and makes a second writer give up after a short timeout:

python
# lock_demo.py - watch "database is locked" happen, then see WAL and the lock in action.
import os
import sqlite3
import tempfile

with tempfile.TemporaryDirectory() as tmp:
    path = os.path.join(tmp, "demo.db")

    setup = sqlite3.connect(path)
    setup.execute("CREATE TABLE notes (id INTEGER PRIMARY KEY, body TEXT)")
    setup.commit()
    print("default journal mode:", setup.execute("PRAGMA journal_mode").fetchone()[0])
    print("after PRAGMA journal_mode = WAL:", setup.execute("PRAGMA journal_mode = WAL").fetchone()[0])
    setup.close()

    # WAL is stored in the database file, so a brand-new connection is already in WAL mode.
    a = sqlite3.connect(path, timeout=0.2)     # timeout = how long to wait for a lock (seconds)
    b = sqlite3.connect(path, timeout=0.2)
    print("new connection sees:", b.execute("PRAGMA journal_mode").fetchone()[0])

    a.execute("BEGIN IMMEDIATE")               # A takes the (single) write lock and holds it
    a.execute("INSERT INTO notes (body) VALUES ('from A')")

    # In WAL mode a reader is not blocked, and sees only COMMITTED data (A has not committed).
    print("reader while A is writing:", b.execute("SELECT COUNT(*) FROM notes").fetchone()[0], "committed rows")
    try:
        b.execute("INSERT INTO notes (body) VALUES ('from B')")   # a second writer has to wait...
    except sqlite3.OperationalError as err:
        print("second writer gave up after the timeout:", err)

    a.commit()                                 # A releases the lock
    b.execute("INSERT INTO notes (body) VALUES ('from B')")       # ...and now B succeeds
    b.commit()
    print("rows now:", b.execute("SELECT COUNT(*) FROM notes").fetchone()[0])
    a.close()
    b.close()
Output6 lines
default journal mode: delete
after PRAGMA journal_mode = WAL: wal
new connection sees: wal
reader while A is writing: 0 committed rows
second writer gave up after the timeout: database is locked
rows now: 2

The rule of thumb: WAL on, a sensible timeout (a few seconds), short write transactions, and one write connection per process is enough for most single-machine AI services. When many separate machines must write, that is the point to move to Postgres.

8.6 A real AI-engineering table: logging LLM calls#

The "You'll hear" table at the top mentioned "the llm_calls table". Almost every AI product ends up with one: a row per model call, so you can answer "what did we spend, what failed, what was slow?" with a GROUP BY instead of a guess. Module 11A builds the full observability picture (11A.1, 11A.2); this section shows the database part with everything you have learned. It is pure standard library and uses made-up rates, so it needs no key:

python
# llm_calls_demo.py - an LLM usage log in SQLite, queried the way you will query real ones.
# Standard library only. Uses an in-memory database, so nothing is written to disk.
import sqlite3

con = sqlite3.connect(":memory:")
con.executescript("""
CREATE TABLE llm_calls (
    id             INTEGER PRIMARY KEY,
    created_at     TEXT    NOT NULL,                  -- ISO 8601 UTC, sorts as text
    provider       TEXT    NOT NULL CHECK (provider IN ('openai', 'anthropic', 'gemini', 'openrouter')),
    model          TEXT    NOT NULL,
    feature        TEXT    NOT NULL,                  -- which product feature made the call
    input_tokens   INTEGER NOT NULL CHECK (input_tokens  >= 0),
    output_tokens  INTEGER NOT NULL CHECK (output_tokens >= 0),
    latency_ms     INTEGER NOT NULL,
    cost_micro_usd INTEGER NOT NULL,                  -- 1_000_000 = one US dollar; an integer avoids float drift
    ok             INTEGER NOT NULL CHECK (ok IN (0, 1)),
    error_type     TEXT                               -- NULL when ok = 1
);
CREATE INDEX idx_llm_calls_created ON llm_calls (created_at);
""")

# Made-up demo rates in US dollars per MILLION tokens: (input, output). NOT real prices.
# $1 per million tokens is exactly 1 micro-dollar per token, so cost = tokens * rate.
DEMO_RATES = {"gpt-6-luna": (1, 4), "claude-haiku-5-5": (2, 8), "gemini-3.8-flash": (1, 3)}

# (created_at, provider, model, feature, input_tokens, output_tokens, latency_ms, ok, error_type)
calls = [
    ("2026-06-01T09:00:00Z", "openai",    "gpt-6-luna",       "triage",  1200,  150,  900, 1, None),
    ("2026-06-01T09:05:00Z", "openai",    "gpt-6-luna",       "triage",  1500,  200, 1100, 1, None),
    ("2026-06-01T10:30:00Z", "anthropic", "claude-haiku-5-5", "summary", 4000,  600, 2400, 1, None),
    ("2026-06-01T11:00:00Z", "gemini",    "gemini-3.8-flash", "triage",   900,  120,  700, 1, None),
    ("2026-06-01T15:45:00Z", "anthropic", "claude-haiku-5-5", "summary", 3500,    0, 3000, 0, "timeout"),
    ("2026-06-02T08:10:00Z", "openai",    "gpt-6-luna",       "triage",  1300,  180, 1000, 1, None),
    ("2026-06-02T08:12:00Z", "gemini",    "gemini-3.8-flash", "summary", 5200,  700, 2100, 1, None),
    ("2026-06-02T13:20:00Z", "anthropic", "claude-haiku-5-5", "summary", 4100,  650, 2600, 1, None),
    ("2026-06-02T13:21:00Z", "openai",    "gpt-6-luna",       "triage",  1100,    0,  400, 0, "rate_limit"),
    ("2026-06-02T17:00:00Z", "gemini",    "gemini-3.8-flash", "triage",   950,  110,  650, 1, None),
]
rows = []
for created_at, provider, model, feature, tin, tout, ms, ok, err in calls:
    in_rate, out_rate = DEMO_RATES[model]
    rows.append((created_at, provider, model, feature, tin, tout, ms, tin * in_rate + tout * out_rate, ok, err))

con.executemany(
    """INSERT INTO llm_calls (created_at, provider, model, feature, input_tokens, output_tokens,
                              latency_ms, cost_micro_usd, ok, error_type)
       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
    rows,
)
con.commit()

print("Cost and tokens per model")
for row in con.execute("""
    SELECT model, COUNT(*) AS calls, SUM(input_tokens + output_tokens) AS tokens,
           ROUND(SUM(cost_micro_usd) / 1000000.0, 4) AS cost_usd
    FROM llm_calls GROUP BY model ORDER BY cost_usd DESC"""):
    print(" ", row)

print("Failure rate per feature (percent)")
for row in con.execute("""
    SELECT feature, COUNT(*) AS calls, ROUND(100.0 * SUM(1 - ok) / COUNT(*), 1) AS failed_pct
    FROM llm_calls GROUP BY feature ORDER BY feature"""):
    print(" ", row)

print("Daily spend (UTC date)")
for row in con.execute("""
    SELECT DATE(created_at) AS day, ROUND(SUM(cost_micro_usd) / 1000000.0, 4) AS cost_usd
    FROM llm_calls GROUP BY day ORDER BY day"""):
    print(" ", row)

print("Slowest successful call per provider")
for row in con.execute("""
    SELECT provider, MAX(latency_ms) AS slowest_ms
    FROM llm_calls WHERE ok = 1 GROUP BY provider ORDER BY provider"""):
    print(" ", row)
con.close()
Output14 lines
Cost and tokens per model
  ('claude-haiku-5-5', 3, 12850, 0.0332)
  ('gemini-3.8-flash', 3, 7980, 0.0098)
  ('gpt-6-luna', 4, 5630, 0.0072)
Failure rate per feature (percent)
  ('summary', 4, 25.0)
  ('triage', 6, 16.7)
Daily spend (UTC date)
  ('2026-06-01', 0.0252)
  ('2026-06-02', 0.0251)
Slowest successful call per provider
  ('anthropic', 2600)
  ('gemini', 2100)
  ('openai', 1100)

Design choices worth copying, and the lesson concept behind each:

Choice Why
cost_micro_usd as an integer Floats cannot represent most decimal fractions exactly, so summing millions of tiny float costs drifts; integer micro-dollars add exactly. Convert to dollars only when displaying (/ 1000000.0).
CHECK (provider IN (...)), CHECK (ok IN (0, 1)) Push invariants into the schema (7.1): a typo such as 'antropic' is rejected instead of creating a ghost row in tomorrow's report.
error_type is NULL on success NULL means "not applicable" (3.3); COUNT(error_type) counts only failures.
ok stored as 0/1 SQLite has no boolean type (4.3); SUM(1 - ok) / COUNT(*) is a failure rate.
Index on created_at Almost every report filters by a time window (7.3).
Cost is computed once, at insert time, from rates kept in your code (or a small prices table) Prices change; storing the computed cost on each row freezes what you actually paid at that time, so a later price change cannot rewrite history. Look up real prices on the providers' pricing pages (03.7); the rates above are invented for the demo.

SQLite has no built-in percentile function, so "p95 latency" is usually computed in Python (or with a window function over the sorted rows); the in-depth treatment is in Module 11A.


Part 9: JSON and text inside SQL#

Reference

Modern databases are asked to store semi-structured data — API payloads, event logs, model outputs — alongside relational rows. SQLite's answer: JSON is just TEXT plus a function library.

9.1 JSON columns and the JSON functions#

ticket_events.payload holds JSON text like '{"from": "pending", "to": "resolved", "by": "agent:1"}'. SQLite has had JSON functions built in by default since 3.38.0 (2022) — around twenty functions (counting the json_group_* aggregates) plus ->/->> operators and json_each/json_tree table-valued functions (source: sqlite.org/json1.html, verified November 2026).

sql
-- Extract a field as text
SELECT id, json_extract(payload, '$.to') AS new_status,
       json_extract(payload, '$.by')   AS actor
FROM ticket_events WHERE kind = 'status_change' ORDER BY id;
-- rows show 'pending'/'resolved' and 'agent:1'/'agent:2'/NULL

-- Filter on a JSON field
SELECT id, kind, payload FROM ticket_events
WHERE json_extract(payload, '$.by') LIKE 'agent:%' ORDER BY id;
-- 6 rows: every event an agent touched

-- The ->> operator is shorthand for json_extract (text); -> keeps JSON type
SELECT id, payload->>'$.to' AS status_to, payload->'$.by' AS actor_json
FROM ticket_events WHERE kind = 'status_change' ORDER BY id LIMIT 4;
-- actor_json shows '"agent:2"' WITH quotes — -> returns JSON, ->> returns text

-- json_each explodes an object into rows you can join/filter
SELECT e.id AS event_id, j.key AS k, j.value AS v
FROM ticket_events e, json_each(e.payload) j
WHERE e.id = 1;
-- from | open
-- to   | pending

-- json_valid guards against malformed payloads before you extract
SELECT id, json_valid(payload) AS is_json FROM ticket_events ORDER BY id;  -- all 1

And JSON can be built in SQL too — json_object, json_array, plus aggregates json_group_array/json_group_object that assemble a JSON array per group (handy for "one row per ticket containing its whole thread"). jsonb_* variants store a binary parse-tree internally (since 3.45) — faster, same results; you never need to choose consciously at this level.

9.2 Full-text search with FTS5#

LIKE '%login%' scans and can't rank. FTS5 is SQLite's built-in full-text engine — an inverted index with BM25 ranking, phrase queries, prefix queries and NEAR. It ships in the amalgamation since SQLite 3.9.0 (2015) and is present in the usual CPython builds (verified: CREATE VIRTUAL TABLE ... USING fts5 works on 3.53.4). If you ever see no such module: fts5, your Python's bundled SQLite was compiled without it — switch to a Python build that includes it rather than fighting it.

sql
CREATE VIRTUAL TABLE messages_fts USING fts5(
    ticket_id UNINDEXED, author UNINDEXED, body,
    content='messages', content_rowid='id');

INSERT INTO messages_fts (rowid, ticket_id, author, body)
SELECT id, ticket_id, author, body FROM messages;

(content='messages' makes it an external content table — FTS5 stores only the index and reads the text back from messages, so no duplication. UNINDEXED columns are stored but not searchable.)

sql
-- Phrase search, ranked best-first via the hidden 'rank' column
SELECT rowid, snippet(messages_fts, 2, '[', ']', '…', 8) AS hit
FROM messages_fts WHERE messages_fts MATCH '"rate limit"' ORDER BY rank;
-- rowid 12: Our nightly sync hit the API [rate limit]…

-- Prefix wildcard + bm25() score (lower/ more negative = better)
SELECT rowid, bm25(messages_fts) AS score
FROM messages_fts WHERE messages_fts MATCH 'refun*' ORDER BY score LIMIT 5;
-- 19: -2.38, 20: -2.38, 38: -2.21

-- Join the hits back to real tables for context
SELECT m.ticket_id, t.subject, m.author,
       snippet(messages_fts, 2, '**', '**', '…', 10) AS hit
FROM messages_fts f
JOIN messages m ON m.id = f.rowid
JOIN tickets t ON t.id = m.ticket_id
WHERE messages_fts MATCH 'webhook'
ORDER BY bm25(messages_fts) LIMIT 5;
-- ticket 17 and ticket 4, with '**webhook**' highlighted in the snippet

FTS5 query syntax: bare words are ANDed, OR/NOT work, "phrase" requires adjacency, word* is prefix, NEAR(a b, 5) is proximity, colname:term filters a column. Tokenizers include unicode61 (default), porter (stemming — "running" matches "run"), trigram (substring search). bm25() returns negative scores where smaller = better — a famous quirk; ORDER BY rank hides it.

9.3 Why embeddings don't go in SQLite#

You will not store embedding vectors in SQLite for real retrieval — and it's worth knowing why, because "just add a vector column" is the obvious wrong turn:

  • A 1,536-dimension float vector is ~6 KB per row; nearest-neighbour search over it is O(n) per query without an ANN index. SQLite has no HNSW/IVF — brute force only. The sqlite-vec extension adds vector KNN to SQLite and suits small prototypes and small devices rather than large corpora: its own docs call it "(currently) brute-force only and meant to run on small devices" (site/guides/binary-quant.md in the sqlite-vec repository), and its README warns that it is pre-v1, so expect breaking changes (both checked November 2026); fine for prototypes (06.5's landscape table covers it).
  • Vector search needs approximate nearest-neighbour indexes (HNSW, IVF — 06.4), metadata filtering, and often hybrid keyword+dense retrieval. That's what vector databases and pgvector provide.
  • The relational data around the vectors — which document, which chunk, which tenant may see it — absolutely does live in SQL. The split you'll see everywhere: vectors in the vector store, metadata and ACLs in SQL (05.8, 06.5).

9.4 SQLite vs PostgreSQL: the differences that matter#

Feature SQLite PostgreSQL
Types 5 storage classes + affinities; STRICT tables opt into real types (3.37+) Strict, rich: uuid, jsonb, arrays, ranges, enums, inet
Auto-increment INTEGER PRIMARY KEY (rowid alias) GENERATED ... AS IDENTITY or SERIAL (legacy)
Case-insensitive text match LIKE is ASCII case-insensitive ILIKE operator; LIKE is case-sensitive
JSON json_extract, ->/->>; text or jsonb blob jsonb type with GIN indexes, @>, ? operators
Full-text FTS5 virtual tables, bm25() tsvector/tsquery/ts_rank + tsvector GIN indexes (different ranking!)
Extensions Compile-time-ish; FTS5, JSON, sqlite-vec CREATE EXTENSION: pgvector, PostGIS, pg_trgm — the AI path's vector home
Concurrency One writer MVCC: many readers + writers
Window functions, CTEs, RETURNING, UPSERT All present (3.25+/3.8+/3.35+/3.24+) All present — same syntax

The through-line: the SQL you learned here runs on Postgres nearly unchanged. What changes is strictness (column types, and Postgres rejecting bare non-grouped columns in GROUP BY queries), the extension ecosystem, and operations (migrations, backups, pooling). When you meet pgvector in 06.5, you'll recognise every clause.


Part 10: Reading and writing good SQL#

Deep-dive

10.1 Reading and writing good SQL#

The habits that separate readable queries from write-only ones:

  • Name things for the reader: snake_case tables/columns (ticket_tags, created_at), one consistent table-name style (singular ticket or plural tickets — this lesson uses plural), id for the surrogate key, <singular_table>_id for foreign keys (customer_id). Consistency beats cleverness.
  • Format like code: keywords uppercase (SELECT, FROM, WHERE), one clause per line, indent subqueries/CTEs, align nothing obsessively. A sqlfmt/sqlfluff formatter exists if your team uses one.
  • Select what you need: SELECT * is for exploration only — it hides schema changes, transfers unneeded data, and breaks INSERT INTO t SELECT * the day a column is added. Name columns.
  • LIMIT while exploring: LIMIT 10 while iterating on a query; remove it (or keep a sane bound) when shipping.
  • ORDER BY anything user-facing: unspecified order is unspecified.
  • Check the plan on slow queries: EXPLAIN QUERY PLAN before theorising.
  • Comment the why: -- 24 = all tag assignments, not tickets teaches the next reader; -- select columns teaches nothing.

10.2 The common-mistakes table#

Mistake What happens Fix
WHERE col = NULL Zero rows, silently IS NULL
UPDATE/DELETE with no WHERE Every row changed Write WHERE first; verify with SELECT
f-string SQL with values SQL injection ?/:name parameters, always
SELECT * in production code Fragile, wasteful Name columns
COUNT(*) after a join Inflated by duplicated rows COUNT(DISTINCT id) or aggregate first
NOT IN (subquery) with NULLs Empty result, mysteriously NOT EXISTS
PRAGMA foreign_keys = ON after writes began Silently off Set right after connect()
Forgetting con.commit() Data vanishes on close with con: or explicit commit
LIKE '%term%' on huge tables Full scan, no ranking FTS5 or dedicated search
Implicit row order Flaky UI, flaky tests ORDER BY always
Dates as DD/MM/YYYY text Wrong sorts, wrong ranges ISO YYYY-MM-DD text or epoch ints
Joins in a loop (N+1) 1,000 queries where 1 would do One JOIN or one IN query
  • "My UPDATE did nothing." → rowcount was 0; the WHERE matched nothing — usually a type mismatch or a NULL you forgot (status = 'Open' vs 'open').
  • "The query is instant in the CLI but slow in the app." → The app is probably sending different SQL or different volume — a function wrapped around an indexed column, a leading-wildcard LIKE '%…', or the query run once per row in a loop. Run EXPLAIN QUERY PLAN on the exact SQL string the app sends.
  • "Duplicate rows appeared after I added a JOIN." → Working as intended; the join multiplied rows. DISTINCT, GROUP BY, or aggregate on the correct side.
  • "The FK constraint didn't fire." → PRAGMA foreign_keys is off by default and a no-op inside a transaction — set it first.
  • "My inserted rows disappeared." → No commit(); the connection closed and rolled back.
  • "database is locked." → Two writers; SQLite allows one. Shorten transactions, set a busy_timeout, turn on WAL (8.5), or move to Postgres.

Common misconceptions#

Misconception Reality
"SQL is just a query language — the database does the rest." The database is the product: constraints, transactions, indexes and the query planner are half the engineering.
"NULL is the same as 0 or empty string." NULL is "unknown/not applicable" — a third truth value that makes =, <, > all return UNKNOWN. IS NULL is the only test.
"Joins combine tables without side effects." Joins multiply rows — one ticket with two tags becomes two rows. COUNT(*) after a join lies; COUNT(DISTINCT id) doesn't.
"SELECT * is convenient and harmless." It hides schema drift, transfers unneeded data, and breaks downstream code when columns change. Name columns in anything shipped.
"I can build SQL strings with f-strings for 'internal' values." Any value not typed literally by you is untrusted — parameters are the only safe channel.
"SQLite is a toy database." It's the most deployed database engine on Earth (every phone, browser, OS ships it) — limited by concurrency, not capability.
"Foreign keys are always enforced." Off by default in SQLite, per-connection, and PRAGMA foreign_keys = ON is a silent no-op inside a transaction.
"An index makes queries faster, so add them everywhere." Indexes speed reads and slow writes — every INSERT updates every index. Index what you filter/join/sort on often.
"with con: closes the connection." It commits or rolls back the transaction and leaves the connection open. con.close() is still your job.
"ORMs mean I don't need to know SQL." ORMs emit SQL; N+1 queries, bad indexes and wrong joins still happen — one layer down.
"Storing JSON in a column is always wrong." Right for pass-through payloads; wrong for fields you filter/join/sort — those want real columns.
"Dates are just text." ISO-8601 text sorts correctly as strings, which is why it works — but it's a convention, not a type. Postgres has real date/timestamptz.

Key takeaways#

  • SQL is declarative and set-based: describe the result; the query planner chooses the path. When slow, run EXPLAIN QUERY PLAN, don't guess.
  • The relational model: tables of typed rows, PRIMARY KEY identity, FOREIGN KEY references, NULL for absent values, schema as the enforced contract.
  • SQLite vs Postgres/MySQL: same core SQL; SQLite is a zero-setup engine perfect for learning, prototyping, tests and small tools; pgvector makes Postgres the vector home later.
  • Core statements mastered: CREATE TABLE + all constraints, INSERT/RETURNING/upsert, SELECT with DISTINCT/aliases/expressions, the full WHERE vocabulary, ORDER BY/LIMIT, UPDATE/DELETE/DROP.
  • NULL is a third truth value — IS NULL/IS NOT NULL always; NULLs vanish from aggregates and comparisons silently.
  • Aggregation: GROUP BY buckets, HAVING filters groups, CASE labels, subqueries/CTEs compose steps, window functions rank and total without collapsing rows.
  • JOINs stitch relationships: INNER keeps matches, LEFT keeps the left side with NULLs, self-joins recurse, UNION stacks, NOT EXISTS finds absences — and joins duplicate rows on purpose.
  • Design for integrity: normalize (each fact once), denormalize only with a reason, index what you query often, wrap multi-statement changes in transactions, version schema changes as migrations, back up with .backup/con.backup().
  • Python safely: ?/:name parameters always (never f-strings), executemany for bulk, with con: for transactions, set pragmas before any DML, row_factory = sqlite3.Row for dict-like rows, pd.read_sql for analysis, ORMs when the schema earns them.
  • Concurrency and AI logging: SQLite has one writer; set a busy_timeout, turn on WAL (PRAGMA journal_mode = WAL), keep write transactions short, and never hold one open across an LLM call. An llm_calls table with integer micro-dollar costs, CHECK constraints and a created_at index answers cost, failure and latency questions with plain GROUP BY.
  • JSON and text in SQL: json_extract/->> for fields, json_each to explode, json_valid to guard; FTS5 for real keyword search; vectors belong to vector stores — SQL keeps the metadata around them.

Terms introduced in this lesson#

Term One-line definition
SQL / Structured Query Language The declarative language for storing and querying relational data
Relational database Data organised into tables linked by keys
Table / row / column / cell The grid: a relation, one record, one attribute, one value
Schema The blueprint: tables, columns, types, constraints
Primary key (PK) Column(s) uniquely identifying each row
Foreign key (FK) Column referencing another table's primary key
Composite key A primary/foreign key spanning multiple columns
Constraint A rule enforced on write (NOT NULL, UNIQUE, CHECK, FK, PK)
NULL "Unknown/not applicable" — distinct from 0, '', false
Three-valued logic TRUE/FALSE/UNKNOWN; only TRUE passes WHERE
Query planner The optimizer choosing scan vs index, join order, sort strategy
EXPLAIN QUERY PLAN Shows the planner's chosen strategy for a query
Index (B-tree) Sorted lookup structure speeding reads, costing writes
Partial / covering index Index on a row subset / including all needed columns
Transaction A bundle of statements committing or rolling back together
ACID Atomicity, Consistency, Isolation, Durability
Migration A versioned schema change applied in order
Normalization (1NF–3NF) Storing each fact once; removing repeating groups and transitive deps
Denormalization Deliberately duplicating data for read speed
SELECT/FROM/WHERE/GROUP BY/HAVING/ORDER BY/LIMIT The core clause vocabulary
Aggregate function COUNT/SUM/AVG/MIN/MAX collapsing rows to one value
DISTINCT Collapse duplicate result values
JOIN (INNER/LEFT/RIGHT/FULL/CROSS) Stitching tables on a key relationship
Self-join Joining a table to itself (hierarchies like manager_id)
UNION/UNION ALL Stacking result sets, deduplicated / not
Anti-join Finding rows with no match (NOT EXISTS, LEFT JOIN ... IS NULL)
Subquery / correlated subquery A SELECT inside a statement; one referencing the outer row
CTE (WITH) A named intermediate result for readable multi-step queries
Window function Aggregate/rank over a row partition without collapsing rows
ROW_NUMBER/RANK/LAG/LEAD Window functions for ranking and row-to-row deltas
CASE SQL's if/elif/else expression
COALESCE/NULLIF/IFNULL NULL-handling functions
Parameterised query SQL text + separate values (?, :name) — injection-proof
SQL injection Attacker-controlled input rewriting your SQL
executemany One statement, many parameter sets
row_factory/sqlite3.Row Dict-like row access by column name
PRAGMA SQLite settings: foreign_keys and busy_timeout apply per connection; journal_mode = WAL persists in the file
autocommit Python 3.12+ opt-out of implicit transactions
ORM Object-relational mapper emitting SQL from Python objects
JSON function (json_extract, ->>, json_each) Querying JSON stored as text
FTS5 SQLite's built-in full-text search virtual table
BM25 The ranking function FTS5 uses (also Lucene's default)
External content table FTS5 table storing only the index; text stays in the source table
sqlite-vec Extension adding vector KNN to SQLite (prototype-grade)
pgvector Postgres extension storing vector columns with ANN indexes
Strict table (STRICT) SQLite 3.37+ opt-in to real type enforcement
Type affinity SQLite's "preferred type" per column (not a hard constraint)
Soft delete Marking rows deleted via a timestamp column instead of DELETE
Keyset pagination WHERE id > :last paging — stable and fast vs OFFSET
View A named, stored SELECT; holds no data of its own
Busy timeout How long a connection waits for a lock before raising database is locked
WAL (write-ahead log) mode journal_mode = WAL: readers and the writer no longer block each other; still one writer
BEGIN IMMEDIATE Starts a transaction that takes the write lock up front
llm_calls table A row-per-model-call usage log (tokens, latency, cost, success) for spend and reliability queries

All terms are also collected in the glossary.


Exercises#

Build tickets.db first (2.3) — and re-run python3 make_tickets_db.py immediately before starting if you ran the mutation demos in 2.5, 4.1 or 8.3 — then work through these against it. Solutions are collapsed — try each before peeking.

  1. Warm-up. List every open ticket whose priority is high or urgent, showing the customer's name. Sort urgent first.
Solution
sql
SELECT t.id, c.name AS customer, t.priority, t.subject
FROM tickets t JOIN customers c ON c.id = t.customer_id
WHERE t.status = 'open' AND t.priority IN ('high', 'urgent')
ORDER BY t.priority DESC, t.id;
Output6 lines
id | customer          | priority | subject
---+-------------------+----------+------------------------------------------------
2  | Alan Turing       | urgent   | Export to CSV times out on large reports
15 | Dennis Ritchie    | urgent   | SSO login broken after IdP certificate rotation
13 | Katherine Johnson | high     | Bulk import fails with 'row 47: bad date'
(3 rows)

Note ORDER BY priority DESC puts urgent before high alphabetically-descending — works here because 'u' > 'h', but a CASE rank would be robust if more priorities existed.

  1. Workload per agent. How many tickets does each agent hold, including agents with none and tickets with no agent? (Hint: FULL OUTER JOIN + GROUP BY on the agent side — and count t.id, not *.)
Solution
sql
SELECT COALESCE(a.name, '(unassigned)') AS agent, COUNT(t.id) AS n
FROM agents a FULL OUTER JOIN tickets t ON t.agent_id = a.id
GROUP BY a.id ORDER BY n DESC;
Output8 lines
agent        | n
-------------+--
Priya Nair   | 7
Tom Becker   | 4
Sam Rivera   | 4
Lena Fischer | 3
(unassigned) | 2
(5 rows)

FULL OUTER JOIN keeps unmatched rows from both sides, which is what this question needs: agents with zero tickets appear (with an all-NULL t.* row), and tickets with no agent land in the NULL-a.id group that COALESCE labels '(unassigned)'. COUNT(t.id) — not COUNT(*) — is required because that preserved-side NULL row would otherwise count as a ticket. A LEFT JOIN driven from tickets (FROM tickets t LEFT JOIN agents a …) can never return a ticketless agent: the join's preserved side is tickets, so the answer only looks right here because every agent happens to hold at least one ticket. GROUP BY a.id (not a.name) is the correct habit — group by the key, display the name.

  1. Satisfaction by plan. Average rating of resolved tickets, grouped by the customer's plan. Which plan is happiest?
Solution
sql
SELECT c.plan, COUNT(*) AS resolved, ROUND(AVG(t.rating), 2) AS avg_rating
FROM tickets t JOIN customers c ON c.id = t.customer_id
WHERE t.status = 'resolved' AND t.rating IS NOT NULL
GROUP BY c.plan ORDER BY c.plan;
Output5 lines
plan       | resolved | avg_rating
-----------+----------+-----------
enterprise | 1        | 4.0
free       | 3        | 4.67
pro        | 4        | 3.5

The status = 'resolved' predicate is the one that matters — tickets 7 and 16 are closed but carry ratings, and would silently join the averages without it. rating IS NOT NULL is redundant here (AVG skips NULLs anyway) but harmless and explicit — good practice.

  1. Latest message per ticket. Using a window function, show the most recent message body and timestamp for each ticket that has messages.
Solution
sql
SELECT m.ticket_id, m.author, m.body, m.created_at
FROM (
    SELECT *, ROW_NUMBER() OVER
        (PARTITION BY ticket_id ORDER BY created_at DESC) AS rn
    FROM messages
) m
WHERE m.rn = 1 ORDER BY m.ticket_id;

19 rows — every ticket except id 8 ("Request: dark mode…"), which has no messages at all. (Find that with an anti-join: WHERE NOT EXISTS (SELECT 1 FROM messages WHERE ticket_id = t.id).)

  1. Popular tags. Which tags label more than one ticket? Show tag name and ticket count.
Solution
sql
SELECT tg.name, COUNT(DISTINCT tt.ticket_id) AS n_tickets
FROM tags tg JOIN ticket_tags tt ON tt.tag_id = tg.id
GROUP BY tg.id
HAVING COUNT(DISTINCT tt.ticket_id) > 1
ORDER BY n_tickets DESC, tg.name;
Output7 lines
name    | n_tickets
--------+----------
bug     | 7
account | 5
billing | 4
how-to  | 4
outage  | 3

COUNT(DISTINCT ...) protects against any accidental duplicate tag rows.

  1. Unanswered tickets. Which tickets have messages but no reply from an agent?
Solution
sql
SELECT t.id, t.subject FROM tickets t
WHERE EXISTS (SELECT 1 FROM messages m
              WHERE m.ticket_id = t.id AND m.author = 'customer')
  AND NOT EXISTS (SELECT 1 FROM messages m
                  WHERE m.ticket_id = t.id AND m.author = 'agent')
ORDER BY t.id;

Result: zero rows — every ticket that got a customer message also got an agent reply in this dataset. (Relaxing to just NOT EXISTS agent returns ticket 8, which has no messages whatsoever — a subtly different question. Check both.)

  1. JSON audit. Which ticket_events were caused by a human agent (as opposed to auto-router or system)? Show the event kind and, for status changes, the new status.
Solution
sql
SELECT id, kind, json_extract(payload, '$.to') AS to_status
FROM ticket_events
WHERE json_extract(payload, '$.by') LIKE 'agent:%'
ORDER BY id;
Output8 lines
id | kind          | to_status
---+---------------+----------
3  | status_change | resolved
6  | status_change | resolved
8  | note          | NULL
9  | status_change | resolved
10 | status_change | resolved
12 | status_change | resolved

Event 8 is a note, so $.to is NULL — the JSON extraction returning NULL for a missing key is the same three-valued logic from 3.3.

  1. Full-text search. Create the FTS5 index from 9.2 — skip the CREATE/INSERT if you already built it there — then find messages mentioning "password" and rank them.
Solution
sql
CREATE VIRTUAL TABLE messages_fts USING fts5(
    ticket_id UNINDEXED, author UNINDEXED, body,
    content='messages', content_rowid='id');
INSERT INTO messages_fts (rowid, ticket_id, author, body)
SELECT id, ticket_id, author, body FROM messages;

SELECT rowid, bm25(messages_fts) AS score
FROM messages_fts WHERE messages_fts MATCH 'password'
ORDER BY score LIMIT 5;

Returns the password-related messages (rowids 1 and 39) ranked by BM25 — try MATCH '"password reset"' for the exact phrase, or 'pass*' for prefix.

  1. Python practice. Write a function status_counts(con) that returns a dict {status: count} for all tickets, using a parameterised query and sqlite3.Row. Then write find_tickets(con, status, min_priority) that returns tickets at or above a priority rank — hint: priorities order low < normal < high < urgent; a CASE expression maps them to numbers.
Solution
python
import sqlite3

def status_counts(con: sqlite3.Connection) -> dict[str, int]:
    con.row_factory = sqlite3.Row
    return {
        row["status"]: row["n"]
        for row in con.execute(
            "SELECT status, COUNT(*) AS n FROM tickets GROUP BY status"
        )
    }

def find_tickets(con: sqlite3.Connection, status: str, min_priority: int):
    rank = """CASE priority WHEN 'low' THEN 1 WHEN 'normal' THEN 2
                     WHEN 'high' THEN 3 WHEN 'urgent' THEN 4 END"""
    return con.execute(
        f"SELECT id, subject, priority FROM tickets "   # f-string ONLY for the CASE text,
        f"WHERE status = ? AND {rank} >= ? ORDER BY id",  # values still parameterised
        (status, min_priority),
    ).fetchall()

status_counts returns {'closed': 2, 'open': 7, 'pending': 3, 'resolved': 8}. The second function shows the one legitimate use of string-building in SQL: injecting a fixed CASE expression you wrote — the ? parameters still carry every user value.

  1. The NULL trap. A colleague writes SELECT COUNT(*) FROM tickets WHERE NOT (rating >= 4) expecting "tickets that aren't top-rated". What does it return, why is it wrong, and what's the fix?
Solution

It returns 3 — only the rated tickets scoring below 4 — because NOT (rating >= 4) is UNKNOWN for every unrated ticket (10 of them), and UNKNOWN rows are dropped. The correct count of "unrated or below 4" is 13:

sql
SELECT COUNT(*) FROM tickets WHERE rating IS NULL OR rating < 4;

The general fix: whenever you negate a comparison on a nullable column, ask what happens to the NULLs — they need an explicit IS NULL branch.

  1. Index investigation. On a copy of tickets.db, run EXPLAIN QUERY PLAN for SELECT * FROM tickets WHERE agent_id IS NULL before and after CREATE INDEX idx_agent ON tickets (agent_id). Does the index help? Explain.
Solution

Before: SCAN tickets. After: SEARCH tickets USING INDEX idx_agent (agent_id=?). Yes — equality lookups on indexed columns become searches. But note IS NULL queries are a special case: the index does store NULLs, so it works. Try the same with WHERE agent_id IS NOT NULL — the planner may still scan because most rows match (an index can't help when the predicate selects nearly everything; cardinality matters more than the operator).

  1. Design critique. Someone proposes one flat table support(id, customer_name, customer_email, subject, status, tag1, tag2, tag3, agent_name). List at least four concrete problems and sketch the normalized alternative.
Solution

Problems: (1) customer email/name duplicated per ticket — updates must touch N rows and can drift; (2) tag1..tag3 caps tags at three and violates 1NF; (3) agent name duplicated and can't represent unassigned cleanly; (4) "all tickets by plan" requires scanning text; (5) no integrity — nothing stops two spellings of the same customer. Normalized: customers, agents, tickets(customer_id, agent_id), tags + ticket_tags(ticket_id, tag_id) — exactly the tickets.db schema.

  1. Where does the money go? Take llm_calls_demo.py from 8.6, delete its four reporting loops and, after con.commit(), write one query that shows each feature, its total cost in dollars and its percentage of all spend, biggest first. (Hint: a scalar subquery gives the grand total — 5.4.)
Solution
sql
SELECT feature,
       ROUND(SUM(cost_micro_usd) / 1000000.0, 4) AS cost_usd,
       ROUND(100.0 * SUM(cost_micro_usd) / (SELECT SUM(cost_micro_usd) FROM llm_calls), 1) AS pct
FROM llm_calls
GROUP BY feature
ORDER BY cost_usd DESC;

Printed one tuple per row with print(row), the output is:

text
('summary', 0.0405, 80.6)
('triage', 0.0098, 19.4)

summary is only 4 of the 10 calls but 80.6% of the (demo) spend, because its prompts are long and it runs on the pricier model. The 100.0 * matters: with 100 * and two integer sums SQLite would do integer division and return the truncated 80 and 19. (The calls are the demo's made-up rows, so only the method carries over.)

Drills: 40 quick queries#

The thirteen exercises above are the deep reps; these forty are the volume reps — one question each, answers collapsed in <details>. Work through them against a freshly built tickets.db (re-run python3 make_tickets_db.py first if you did the mutation demos in 2.5, 4.1 or 8.3), and type each query yourself before peeking: the goal is fluent SELECT composition, not recognition. They run roughly in lesson order — filtering and NULLs, aggregation, expressions and dates, subqueries/CTEs/windows, joins, then JSON and FTS5. Every output below is real, run on SQLite 3.53.4.

  1. Show the subject and status of ticket 7.
Answer
sql
SELECT subject, status FROM tickets WHERE id = 7;
Output4 lines
subject                                 | status
----------------------------------------+-------
Dashboard charts render blank on Safari | closed
(1 rows)
  1. List the subjects of all closed tickets, alphabetically.
Answer
sql
SELECT subject FROM tickets WHERE status = 'closed' ORDER BY subject;
Output5 lines
subject
---------------------------------------
Dashboard charts render blank on Safari
Export API documentation is outdated
(2 rows)
  1. How many tickets arrived through the chat channel?
Answer
sql
SELECT COUNT(*) AS n FROM tickets WHERE channel = 'chat';
Output4 lines
n
-
5
(1 rows)
  1. Name and email of every enterprise customer.
Answer
sql
SELECT name, email FROM customers WHERE plan = 'enterprise' ORDER BY name;
Output5 lines
name           | email
---------------+-------------------
Dennis Ritchie | dennis@example.com
Grace Hopper   | grace@example.com
(2 rows)
  1. The 4 newest tickets created on or after 2026-05-20.
Answer
sql
SELECT id, subject, created_at FROM tickets WHERE created_at >= '2026-05-20' ORDER BY created_at DESC LIMIT 4;
Output7 lines
id | subject                                   | created_at
---+-------------------------------------------+---------------------
20 | Password reset email lands in spam folder | 2026-05-24T13:50:00Z
19 | Double charge on May invoice              | 2026-05-23T10:02:00Z
18 | Cannot delete workspace — 'in use' error  | 2026-05-22T17:41:00Z
17 | Webhook signature validation failing      | 2026-05-21T08:27:00Z
(4 rows)
  1. The 5 shortest ticket subjects.
Answer
sql
SELECT id, subject, LENGTH(subject) AS len FROM tickets ORDER BY len, id LIMIT 5;
Output8 lines
id | subject                            | len
---+------------------------------------+----
19 | Double charge on May invoice       | 28
3  | Invoice shows wrong VAT amount     | 30
10 | Refund for cancelled annual plan   | 32
5  | How do I add a second admin user?  | 33
1  | Cannot log in after password reset | 34
(5 rows)
  1. Which channels appear in tickets? (distinct values)
Answer
sql
SELECT DISTINCT channel FROM tickets ORDER BY channel;
Output6 lines
channel
-------
chat
email
phone
(3 rows)
  1. Ids and subjects of all urgent tickets.
Answer
sql
SELECT id, subject FROM tickets WHERE priority = 'urgent' ORDER BY id;
Output7 lines
id | subject
---+------------------------------------------------
2  | Export to CSV times out on large reports
9  | Login loop on mobile app after update
15 | SSO login broken after IdP certificate rotation
19 | Double charge on May invoice
(4 rows)
  1. How many tickets are open or pending?
Answer
sql
SELECT COUNT(*) AS n FROM tickets WHERE status IN ('open', 'pending');
Output4 lines
n
--
10
(1 rows)
  1. Tickets whose subject mentions 'password'.
Answer
sql
SELECT id, subject FROM tickets WHERE subject LIKE '%password%' ORDER BY id;
Output5 lines
id | subject
---+------------------------------------------
1  | Cannot log in after password reset
20 | Password reset email lands in spam folder
(2 rows)
  1. How many tickets have no rating?
Answer
sql
SELECT COUNT(*) AS n FROM tickets WHERE rating IS NULL;
Output4 lines
n
--
10
(1 rows)
  1. Tickets that are unrated or rated below 3.
Answer
sql
SELECT COUNT(*) AS n FROM tickets WHERE rating IS NULL OR rating < 3;
Output4 lines
n
--
11
(1 rows)
  1. The last 3 tickets created (OFFSET drill).
Answer
sql
SELECT id, subject, created_at FROM tickets ORDER BY created_at LIMIT 3 OFFSET 17;
Output6 lines
id | subject                                   | created_at
---+-------------------------------------------+---------------------
18 | Cannot delete workspace — 'in use' error  | 2026-05-22T17:41:00Z
19 | Double charge on May invoice              | 2026-05-23T10:02:00Z
20 | Password reset email lands in spam folder | 2026-05-24T13:50:00Z
(3 rows)
  1. What are the first 3 rows of ORDER BY rating ASC? (watch NULLs)
Answer
sql
SELECT id, rating FROM tickets ORDER BY rating, id LIMIT 3;
Output6 lines
id | rating
---+-------
2  | NULL
4  | NULL
5  | NULL
(3 rows)
  1. Ticket count per channel.
Answer
sql
SELECT channel, COUNT(*) AS n FROM tickets GROUP BY channel ORDER BY channel;
Output6 lines
channel | n
--------+---
chat    | 5
email   | 13
phone   | 2
(3 rows)
  1. How many tickets have at least one message?
Answer
sql
SELECT COUNT(DISTINCT ticket_id) AS n FROM messages;
Output4 lines
n
--
19
(1 rows)
  1. Average number of messages per ticket that has messages.
Answer
sql
SELECT ROUND(AVG(n), 2) AS avg_msgs FROM (SELECT COUNT(*) AS n FROM messages GROUP BY ticket_id);
Output4 lines
avg_msgs
--------
2.11
(1 rows)
  1. Which agent holds the most tickets? Show name and count.
Answer
sql
SELECT a.name, COUNT(*) AS n FROM tickets t JOIN agents a ON a.id = t.agent_id GROUP BY a.id ORDER BY n DESC, a.id LIMIT 1;
Output4 lines
name       | n
-----------+--
Priya Nair | 7
(1 rows)
  1. How many tickets has each plan's customers filed in total?
Answer
sql
SELECT c.plan, COUNT(*) AS n FROM tickets t JOIN customers c ON c.id = t.customer_id GROUP BY c.plan ORDER BY c.plan;
Output6 lines
plan       | n
-----------+--
enterprise | 4
free       | 8
pro        | 8
(3 rows)
  1. Which statuses have fewer than 3 tickets?
Answer
sql
SELECT status, COUNT(*) AS n FROM tickets GROUP BY status HAVING COUNT(*) < 3 ORDER BY status;
Output4 lines
status | n
-------+--
closed | 2
(1 rows)
  1. Ticket count per priority.
Answer
sql
SELECT priority, COUNT(*) AS n FROM tickets GROUP BY priority ORDER BY priority;
Output7 lines
priority | n
---------+--
high     | 6
low      | 4
normal   | 6
urgent   | 4
(4 rows)
  1. Total tag assignments in ticket_tags.
Answer
sql
SELECT COUNT(*) AS n FROM ticket_tags;
Output4 lines
n
--
24
(1 rows)
  1. Tickets created per weekday (0 = Sunday).
Answer
sql
SELECT strftime('%w', created_at) AS weekday, COUNT(*) AS n FROM tickets GROUP BY weekday ORDER BY weekday;
Output10 lines
weekday | n
--------+--
0       | 3
1       | 3
2       | 2
3       | 3
4       | 3
5       | 3
6       | 3
(7 rows)
  1. Average ticket-subject length across all tickets.
Answer
sql
SELECT ROUND(AVG(LENGTH(subject)), 1) AS avg_len FROM tickets;
Output4 lines
avg_len
-------
37.2
(1 rows)
  1. Show unassigned tickets with a readable agent label.
Answer
sql
SELECT t.id, t.subject, COALESCE(a.name, '(unassigned)') AS agent FROM tickets t LEFT JOIN agents a ON a.id = t.agent_id WHERE t.agent_id IS NULL ORDER BY t.id;
Output5 lines
id | subject                                   | agent
---+-------------------------------------------+-------------
5  | How do I add a second admin user?         | (unassigned)
13 | Bulk import fails with 'row 47: bad date' | (unassigned)
(2 rows)
  1. Average days from ticket creation to resolution.
Answer
sql
SELECT ROUND(AVG(julianday(resolved_at) - julianday(created_at)), 2) AS avg_days FROM tickets WHERE resolved_at IS NOT NULL;
Output4 lines
avg_days
--------
1.15
(1 rows)
  1. Tickets rated above the average rating.
Answer
sql
SELECT id, rating FROM tickets WHERE rating > (SELECT AVG(rating) FROM tickets WHERE rating IS NOT NULL) ORDER BY rating DESC, id;
Output10 lines
id | rating
---+-------
1  | 5
10 | 5
19 | 5
3  | 4
7  | 4
14 | 4
20 | 4
(7 rows)
  1. Tickets with more messages than ticket 5 has.
Answer
sql
SELECT t.id FROM tickets t WHERE (SELECT COUNT(*) FROM messages m WHERE m.ticket_id = t.id) > (SELECT COUNT(*) FROM messages WHERE ticket_id = 5) ORDER BY t.id;
Output5 lines
id
--
1
9
(2 rows)
  1. Open tickets with their customers' names, via a CTE.
Answer
sql
WITH open_tickets AS (SELECT * FROM tickets WHERE status = 'open') SELECT c.name, t.subject FROM open_tickets t JOIN customers c ON c.id = t.customer_id ORDER BY c.name;
Output10 lines
name              | subject
------------------+------------------------------------------------
Alan Turing       | Export to CSV times out on large reports
Barbara Liskov    | Request: dark mode for the admin panel
Dennis Ritchie    | SSO login broken after IdP certificate rotation
Frances Allen     | Cannot delete workspace — 'in use' error
Grace Hopper      | Search returns stale results after edit
Katherine Johnson | Bulk import fails with 'row 47: bad date'
Margaret Hamilton | How do I add a second admin user?
(7 rows)
  1. Rank agents by ticket count with RANK() — what happens with ties?
Answer
sql
SELECT name, n, RANK() OVER (ORDER BY n DESC) AS rnk FROM (SELECT a.name, COUNT(*) AS n FROM tickets t JOIN agents a ON a.id = t.agent_id GROUP BY a.id) ORDER BY rnk, name;
Output7 lines
name         | n | rnk
-------------+---+----
Priya Nair   | 7 | 1
Sam Rivera   | 4 | 2
Tom Becker   | 4 | 2
Lena Fischer | 3 | 4
(4 rows)
  1. Running total of ratings across tickets, in id order.
Answer
sql
SELECT id, rating, SUM(rating) OVER (ORDER BY id) AS running_total FROM tickets WHERE rating IS NOT NULL ORDER BY id LIMIT 6;
Output9 lines
id | rating | running_total
---+--------+--------------
1  | 5      | 5
3  | 4      | 9
6  | 3      | 12
7  | 4      | 16
9  | 2      | 18
10 | 5      | 23
(6 rows)
  1. For tickets 1, 6 and 9: the agent and that agent's manager.
Answer
sql
SELECT t.id, a.name AS agent, m.name AS manager FROM tickets t JOIN agents a ON a.id = t.agent_id LEFT JOIN agents m ON m.id = a.manager_id WHERE t.id IN (1, 6, 9) ORDER BY t.id;
Output6 lines
id | agent      | manager
---+------------+-----------
1  | Priya Nair | Tom Becker
6  | Priya Nair | Tom Becker
9  | Priya Nair | Tom Becker
(3 rows)
  1. Tickets tagged with BOTH 'bug' and 'outage'.
Answer
sql
SELECT t.id, t.subject FROM tickets t WHERE t.id IN (SELECT ticket_id FROM ticket_tags tt JOIN tags g ON g.id = tt.tag_id WHERE g.name = 'bug') AND t.id IN (SELECT ticket_id FROM ticket_tags tt JOIN tags g ON g.id = tt.tag_id WHERE g.name = 'outage') ORDER BY t.id;
Output5 lines
id | subject
---+-----------------------------------------
2  | Export to CSV times out on large reports
6  | API rate limit hit during nightly sync
(2 rows)
  1. The 5 tickets with the most messages, with their subjects.
Answer
sql
SELECT m.ticket_id, COUNT(*) AS n_messages, t.subject FROM messages m JOIN tickets t ON t.id = m.ticket_id GROUP BY m.ticket_id ORDER BY n_messages DESC, m.ticket_id LIMIT 5;
Output8 lines
ticket_id | n_messages | subject
----------+------------+-----------------------------------------
1         | 3          | Cannot log in after password reset
9         | 3          | Login loop on mobile app after update
2         | 2          | Export to CSV times out on large reports
3         | 2          | Invoice shows wrong VAT amount
4         | 2          | Webhook deliveries failing with 500
(5 rows)
  1. All distinct person names across customers and agents.
Answer
sql
SELECT name FROM customers UNION SELECT name FROM agents ORDER BY name;
Output17 lines
name
-----------------
Ada Lovelace
Alan Turing
Barbara Liskov
Dennis Ritchie
Frances Allen
Grace Hopper
Katherine Johnson
Ken Thompson
Lena Fischer
Margaret Hamilton
Priya Nair
Radia Perlman
Sam Rivera
Tom Becker
(14 rows)
  1. Each agent's name and their manager's name (self-join).
Answer
sql
SELECT a.name AS agent, m.name AS manager FROM agents a LEFT JOIN agents m ON m.id = a.manager_id ORDER BY agent;
Output7 lines
agent        | manager
-------------+-------------
Lena Fischer | NULL
Priya Nair   | Tom Becker
Sam Rivera   | Lena Fischer
Tom Becker   | Lena Fischer
(4 rows)
  1. Tags that label exactly one ticket.
Answer
sql
SELECT g.name, COUNT(*) AS n FROM tags g JOIN ticket_tags tt ON tt.tag_id = g.id GROUP BY g.id HAVING COUNT(*) = 1 ORDER BY g.name;
Output4 lines
name            | n
----------------+--
feature-request | 1
(1 rows)
  1. ticket_events count per kind.
Answer
sql
SELECT kind, COUNT(*) AS n FROM ticket_events GROUP BY kind ORDER BY kind;
Output6 lines
kind          | n
--------------+--
assigned      | 2
note          | 1
status_change | 9
(3 rows)
  1. Events that moved a ticket to 'resolved', with the actor.
Answer
sql
SELECT id, ticket_id, json_extract(payload, '$.by') AS actor FROM ticket_events WHERE json_extract(payload, '$.to') = 'resolved' ORDER BY id;
Output8 lines
id | ticket_id | actor
---+-----------+--------
3  | 1         | agent:2
6  | 3         | agent:1
9  | 9         | agent:2
10 | 10        | agent:1
12 | 19        | agent:1
(5 rows)
  1. FTS5: messages mentioning 'webhook', ranked by bm25 (build messages_fts as in 9.2 first).
Answer
sql
SELECT rowid, bm25(messages_fts) AS score FROM messages_fts WHERE messages_fts MATCH 'webhook' ORDER BY score;
Output5 lines
rowid | score
------+--------------------
33    | -3.1477021329364976
8     | -2.7482475475384645
(2 rows)

Where you'll use this in the AI path#

SQL is the connective tissue of the whole path — nearly every later module stores or queries relational data:

Later lesson What it does with SQL
05.8 Metadata design Designs the typed metadata fields that become columns/filters; the "side table" pattern is this lesson's normalization
06.5 Vector databases pgvector puts vector columns inside Postgres — same CREATE TABLE, same WHERE, plus distance operators
06.7 Keyword search and BM25 FTS5's MATCH/bm25() you met in 9.2, in depth
10A.2 Building eval datasets "SQLite / DuckDB table" is a first-class eval-dataset store — query cases with SELECT, join against logs
11A.2 Metrics, SLOs and alerting Cost/usage data (a table like 8.6's llm_calls, or the llm_cost_usd_total counter) is exactly the GROUP BY/SUM queries of Part 5
12.5 Guardrails and output validation Model-written SQL is untrusted input — the injection lesson of 8.2 applied to LLM output
01B.11 NumPy and pandas pd.read_sql(con) turns your queries into DataFrames for analysis

Check yourself#

  1. What's the difference between a primary key and a foreign key?
  2. Why does WHERE rating > 3 silently exclude unrated tickets, and how do you include them?
  3. COUNT(*) vs COUNT(rating) on tickets — which returns 20 and which 10, and why?
  4. Name the three JOIN types and when you'd pick LEFT JOIN over INNER JOIN.
  5. A query joins tickets to ticket_tags and returns 24 rows for 20 tickets. Bug or feature? How do you get the right ticket count?
  6. What's the difference between WHERE and HAVING?
  7. When would you use a CTE instead of a subquery?
  8. What does a window function do that GROUP BY cannot?
  9. Why is PRAGMA foreign_keys = ON sometimes a silent no-op in Python's sqlite3?
  10. Show the safe way to run SELECT * FROM users WHERE email = ? with a user's email — and why f-strings are forbidden.
  11. What does with con: do on success, on exception, and what does it not do?
  12. When should a field be a real column vs a JSON blob? Give the rule of thumb.
  13. What is FTS5, and what does MATCH '"exact phrase"' do that LIKE '%exact phrase%' can't?
  14. You need "vectors + similarity search" for a RAG app. Why doesn't a vector column in SQLite cut it, and where does this path send you?
  15. Your FastAPI service and a background eval job both write to one SQLite file and you see database is locked. Name the two settings you would reach for first, and the one habit that matters most inside write transactions.

Further resources#

  • SQLite documentation — the authoritative reference; lang.html (SQL syntax), lang_corefunc.html (functions), fts5.html, json1.html are the four pages this lesson draws on.
  • Python sqlite3 docs — the DB-API layer: connections, transactions, row_factory, autocommit.
  • SQLBolt — free interactive SQL tutorials; the fastest way to drill SELECT/JOIN/GROUP BY reps.
  • Use The Index, Luke — the classic free book on how indexes actually work; read it before your first slow-query incident.
  • pgvector README — the Postgres extension you'll meet in 06.5.
  • SQLite FAQ on concurrency — the honest limits (one writer) and when they matter.
  • SQLite write-ahead logging — how WAL mode works, what it changes for readers and the writer, and where it does not apply (network file systems); the source for 8.5.

← 00.6 — HTTP, REST and JSON | Module 00 overview | 00.8 — Reading API Documentation →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close