Data Modeling, Queries and Migrations

Article · 7:00

Constraints that hold, the rowid and WITHOUT ROWID, joins and window functions, and schema migrations in an engine with almost no ALTER TABLE.

The rowid is the thing to understand first. Every ordinary SQLite table has a hidden 64-bit rowid which is its physical key - the table is a B-tree ordered by it. Declaring a column INTEGER PRIMARY KEY makes that column an alias for the rowid rather than a separate indexed column, so lookups by it are a direct B-tree descent with no secondary index to traverse. Declaring INTEGER PRIMARY KEY is therefore meaningfully faster than declaring INT PRIMARY KEY, which is a different thing entirely.

WITHOUT ROWID tables store rows in a B-tree keyed by the declared primary key itself. They are smaller and faster for tables with a natural key that is not an integer - a lookup table keyed by code, a junction table keyed by its pair.

Constraints. SQLite supports NOT NULL, CHECK, UNIQUE, PRIMARY KEY and FOREIGN KEY, and with STRICT and foreign_keys = ON they are genuinely enforced. One historical wart: a column declared PRIMARY KEY that is not INTEGER PRIMARY KEY can still contain NULL in non-STRICT tables, for backwards compatibility with a bug from 2001. Write NOT NULL explicitly.

Queries. SQLite supports a surprising amount of modern SQL: CTEs including recursive ones, window functions since 3.25, RETURNING since 3.35, and upsert via ON CONFLICT DO UPDATE. For practical purposes you can write the same analytical SQL you would write against PostgreSQL. What is missing is mostly server-side: no stored procedures, no RIGHT JOIN before 3.39, and no full outer join before that either.

Migrations are the part that is genuinely harder. SQLite's ALTER TABLE can add a column, rename a table or column, and drop a column - and nothing else. You cannot change a column's type, add or remove a constraint, or reorder columns.

The supported procedure for anything else is the twelve-step dance from the official documentation, and the short version is: create a new table with the shape you want, copy the data across, drop the old table, rename the new one. The critical details are that it must happen inside a transaction, that foreign_keys must be off during it (otherwise the copy trips its own constraints), and that PRAGMA foreign_key_check must be run before committing.

PRAGMA user_version is an integer in the file header, intended precisely for schema versioning. Use it: your application reads it on open and applies each migration above it in order.

Laboratory exercise 2 - two competing models, and a migration.

Design two schemas for the capstone's expense tracker. Suggested contrast: a normalised model with expense, category and tag tables and a junction, against a denormalised model with categories as text and tags as a JSON array. Implement both.

Write the representative queries against each: insert an expense, list a month, total by category, find by tag, and search notes by text.

Then write a migration that takes model A to a changed version of model A - add a NOT NULL column with a default, and tighten an existing CHECK - using the twelve-step procedure. Prove it is safe: run it against the loaded database, verify with foreign_key_check and integrity_check, and show the row count unchanged.

Deliverable: both schemas, the queries, the migration script with user_version handling, the verification output, and a page arguing for one model against the stated access patterns. Include what the migration would cost on a one-gigabyte file, measured rather than estimated.

-- ------------------------------------------------------------------
-- rowid, and why INTEGER PRIMARY KEY is not the same as INT PRIMARY KEY
-- ------------------------------------------------------------------
CREATE TABLE fast (id INTEGER PRIMARY KEY, v TEXT) STRICT;
--                     ^^^^^^^^^^^^^^^^^^^ an ALIAS for the rowid. The
--                     table IS a B-tree keyed on this. No second index.

CREATE TABLE slower (id INT PRIMARY KEY, v TEXT) STRICT;
--                      ^^^ a normal column with a UNIQUE index over it,
--                      plus the hidden rowid. Two structures, two
--                      lookups, more space.

-- WITHOUT ROWID: right for a natural, non-integer key.
CREATE TABLE currency (
    code TEXT PRIMARY KEY,          -- 'GBP', 'USD'
    name TEXT NOT NULL,
    minor_units INTEGER NOT NULL
) WITHOUT ROWID, STRICT;

-- A junction table, keyed by its pair, stored once rather than twice:
CREATE TABLE expense_tag (
    expense_id INTEGER NOT NULL REFERENCES expense(id) ON DELETE CASCADE,
    tag_id     INTEGER NOT NULL REFERENCES tag(id)     ON DELETE CASCADE,
    PRIMARY KEY (expense_id, tag_id)
) WITHOUT ROWID, STRICT;

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

-- ------------------------------------------------------------------
-- Modern SQL that SQLite does support.
-- ------------------------------------------------------------------

-- Upsert, with RETURNING (3.35+):
INSERT INTO category (name) VALUES ('food')
ON CONFLICT (name) DO UPDATE SET name = excluded.name
RETURNING id;

-- Window functions (3.25+): a running total within each month.
SELECT
    strftime('%Y-%m', spent_at) AS month,
    spent_at, amount_minor,
    sum(amount_minor) OVER (
        PARTITION BY strftime('%Y-%m', spent_at)
        ORDER BY spent_at
        ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
    ) AS running_total,
    rank() OVER (
        PARTITION BY strftime('%Y-%m', spent_at)
        ORDER BY amount_minor DESC
    ) AS size_rank
FROM expense
WHERE spent_at >= '2026-01-01'
ORDER BY spent_at;

-- A CTE and a join, for the monthly report:
WITH monthly AS (
    SELECT c.name AS category,
           strftime('%Y-%m', e.spent_at) AS month,
           sum(e.amount_minor) AS total,
           count(*) AS n
    FROM expense e
    JOIN category c ON c.id = e.category_id
    GROUP BY category, month
)
SELECT month, category, total, n,
       round(100.0 * total / sum(total) OVER (PARTITION BY month), 1) AS pct
FROM monthly
ORDER BY month DESC, total DESC;

-- JSON, stored in TEXT and queried with the json functions:
SELECT id, json_extract(metadata, '$.merchant') AS merchant
FROM expense
WHERE json_extract(metadata, '$.reimbursable') = 1;

-- ------------------------------------------------------------------
-- MIGRATIONS. ALTER TABLE does almost nothing, so this is the
-- supported twelve-step procedure, compressed.
-- ------------------------------------------------------------------

-- What ALTER TABLE CAN do, which is the whole list:
ALTER TABLE expense ADD COLUMN reimbursed INTEGER NOT NULL DEFAULT 0;
ALTER TABLE expense RENAME COLUMN note TO description;
ALTER TABLE expense RENAME TO expense_old;
ALTER TABLE expense_old DROP COLUMN description;   -- 3.35+
-- It CANNOT change a type, add or remove a constraint, or reorder.

-- Everything else looks like this. Note the order carefully:
PRAGMA foreign_keys = OFF;      -- MUST be off: the copy would otherwise
                                -- trip constraints against a half-built
                                -- table. This is step one, outside the
                                -- transaction.
BEGIN;

  CREATE TABLE expense_new (
      id          INTEGER PRIMARY KEY,
      category_id INTEGER NOT NULL REFERENCES category(id) ON DELETE RESTRICT,
      amount_minor INTEGER NOT NULL CHECK (amount_minor > 0),
      currency    TEXT    NOT NULL REFERENCES currency(code),
      spent_at    TEXT    NOT NULL CHECK (spent_at LIKE '____-__-__%'),
      description TEXT,
      -- the new column, with the tightened constraint:
      reimbursed  INTEGER NOT NULL DEFAULT 0 CHECK (reimbursed IN (0,1)),
      metadata    TEXT    CHECK (metadata IS NULL OR json_valid(metadata))
  ) STRICT;

  INSERT INTO expense_new (id, category_id, amount_minor, currency,
                           spent_at, description, reimbursed, metadata)
  SELECT id, category_id, amount_minor, currency,
         spent_at, description, 0, metadata
  FROM expense;

  DROP TABLE expense;
  ALTER TABLE expense_new RENAME TO expense;

  -- Indexes and triggers were dropped with the old table. Recreate
  -- them here, inside the same transaction, or the first query after
  -- the migration does a table scan.
  CREATE INDEX expense_by_date     ON expense (spent_at);
  CREATE INDEX expense_by_category ON expense (category_id, spent_at);

  PRAGMA foreign_key_check;       -- MUST return no rows before COMMIT
  PRAGMA user_version = 3;        -- the version this migration produces

COMMIT;
PRAGMA foreign_keys = ON;

-- The application reads user_version on open and applies each
-- migration above it, in order, in a transaction:
PRAGMA user_version;

Discussion

No questions on this topic yet. Sign in to ask the first one.