Why “a few TSV files” stops working, and a relational database (data organised as tables that reference each other) starts
The minimum SQL (Structured Query Language, the standard way to ask a database questions) you will use every working day
What SQLite is — an embedded database (lives inside your program, not on a server)
Driving SQLite from Rust with the rusqlite crate
The pain that motivates today
You’re managing a microbial strain collection. The lab uses a shared TSV file.
Two team members type the same strain’s name slightly differently.
A row gets pasted twice; contradictory values, no way to tell which is right.
Two Excel users save the same TSV; second save silently wins.
A relational database in one picture
A relational database (data organised as tables that reference each other) stores facts as rows in named tables. Each row is a tuple (a single row’s values bundled together).
A table is rows and columns; the primary key names each row.
Tables, rows, columns, types
A table is a named grid.
A row is one record — a tuple of column values.
A column has a name and a declared type. SQLite’s main types:
Declared type
Used for
INTEGER
counts, IDs, years
REAL
floating-point values (OD, fractions)
TEXT
strings (names, free text)
INTEGER PRIMARY KEY
auto-incrementing row ID
Primary keys — one row, one identity
The primary key uniquely identifies a row. Two rows may agree on every other column, but never on the primary key.
CREATETABLE strain ( strain_id INTEGERPRIMARYKEY, strain_name TEXT NOTNULL, species TEXT NOTNULL, isolation_source TEXT, year_isolated INTEGER);
INTEGER PRIMARY KEY auto-assigns the next free integer on INSERT. NOT NULL makes the column mandatory.
Aggregation collapses many rows into one summary row per group.
-- How many strains per species?SELECT species, COUNT(*) AS nFROM strainGROUPBY speciesORDERBY n DESC;
-- Mean OD per medium, only media measured >= 3 timesSELECT medium, AVG(od600_24h) AS mean_od, COUNT(*) AS nFROM assayGROUPBY mediumHAVINGCOUNT(*) >=3;
Input: many assay rows. Output: one row per medium with AVG(od600_24h) per group.
SELECT as a pipeline
The clauses don’t run in writing order — they run as a pipeline.
Stage 1 — FROM: pick the input table(s).
Stage 2 — WHERE: filter rows.
Stage 3 — GROUP BY: bucket rows by a key.
SELECT pipeline (continued)
Stage 4 — SELECT + aggregations: compute columns per group.
Stage 5 — ORDER BY + LIMIT: sort and trim.
WHERE filters individual rows before grouping; HAVING filters whole groups after aggregation.
JOIN — combine two tables
A join (stitching two tables together so a single row in the result contains columns from both) is how we follow a foreign key.
SELECT s.strain_name, s.species, a.medium, a.od600_24hFROM strain AS sINNERJOIN assay AS a ON a.strain_id = s.strain_idWHERE s.species ='Escherichia coli'ORDERBY a.date_measured;
AS s, AS a — table aliases, saves typing
ON a.strain_id = s.strain_id — the join condition
INNER JOIN (keep only rows that have a match on both sides) is the default and most common shape
INNER JOIN — visualised
Start: strain and assay tables, no joined rows yet.
Match #1: assay strain_id = 1 joins to strain row 1.
INNER JOIN — visualised (continued)
Match #2: a second assay reuses the same strain row (one-to-many).
All matching pairs: one output row per (strain, assay) match.
NATURAL JOIN — the shortcut
NATURAL JOIN auto-joins on every column the two tables share by name.
SELECT s.strain_name, COUNT(a.assay_id) AS nFROM strain AS sLEFTJOIN assay AS a ON a.strain_id = s.strain_idGROUPBY s.strain_nameORDERBY n;
LEFT JOIN keeps every left-table row, filling NULL on the right when no match exists. A strain with zero assays shows up with n = 0; INNER JOIN would drop it silently.
LEFT JOIN keeps unmatched left rows; right-side fields become NULL.
INNER vs LEFT vs NATURAL — when to use which
Want
Use
Only rows present in both tables
INNER JOIN ... ON ...
Every row from one table, even unmatched
LEFT JOIN ... ON ...
Quick prototype on a tidy schema
NATURAL JOIN
Real, long-lived code
INNER or LEFT with explicit ON
What is SQLite?
A relational database engine packaged as a C library, not a server.
One .db file is one entire database (the schema — the table definitions, columns, types, keys — plus every row of data)
No daemon, no port, no user accounts, no configuration
The most-deployed database in the world — every Android app, every iPhone, every browser, most desktop software, every airliner
SQLite vs. client/server
SQLite is a library, not a server.
Why SQLite fits bioinformatics
One file — fits the “one analysis directory” workflow we already use
Embedded — no extra service to keep alive on a shared cluster
Cross-platform — .db files work unchanged on Linux, macOS, Windows
Single writer — fine when one pipeline owns the data
Concretely, where a .sqlite file shows up in practice:
Use case
Why a file works
Public annotation dumps (e.g. genome browsers)
One download, no server to install
Your lab’s strain or sample collection
Email or rsync one .db to a collaborator
Pipeline metadata / per-sample results
Embedded next to the output directory
Test fixtures for analysis code
Open in-memory, seed, throw away
The sqlite3 CLI
$ sqlite3 strains.db # opens (creates if missing)sqlite> SELECT * FROM strain LIMIT 3;-- runs SQL
Dot-commands are CLI-only features (no trailing ;):
.tables -- list table names
.schema strain -- show CREATE TABLE
.headers on -- show column names in SELECT output
.mode column -- align rows as a table
.read seed.sql -- run SQL from a file
.import data.csv t -- load CSV into table t
.quit
[dependencies]rusqlite={ version ="0.31", features =["bundled"] }
rusqlite is a thin wrapper (Rust code that calls SQLite’s underlying C functions for you — you write Rust, the C library does the work) around the SQLite C library.
The bundled feature compiles SQLite from source into your binary — no system library required. Costs ~30 s on the first build, then cached.
The rusqlite read pipeline
Four lines of Rust, four conceptual stages:
Step 1 — Connection::open(path): open (or create) the .db file.
Step 2 — conn.prepare(...): compile SQL into a reusable prepared statement.
A transaction (a group of statements treated as one indivisible unit) gives you two things:
Atomicity (all the writes happen together, or none of them do) — if anything fails between BEGIN and COMMIT, the database rolls back to its prior state.
Performance — one fsync (force the disk to actually save) at COMMIT, instead of one per row.
One fsync per transaction beats one fsync per row.
Transactions in rusqlite
let tx = conn.transaction()?;{letmut stmt = tx.prepare("INSERT INTO strain (strain_name, species, year_isolated) VALUES (?1, ?2, ?3)", )?;for s in strains { stmt.execute(rusqlite::params![s.name, s.species, s.year])?;}}tx.commit()?;
#[test] marks a function cargo test will run; open_in_memory() gives each test its own fresh database.
What we deliberately leave out
UPDATE, DELETE, ALTER TABLE — same parameter pattern as INSERT
Indexes — an index (a pre-sorted lookup the database builds for one column) turns “scan a million rows” into “jump straight to the matches”; matters once a table gets big
EXPLAIN QUERY PLAN — see which indexes the engine actually used