SQLITE GO TUTORIAL · DATABASE/SQL · 19 LESSONS
SQLite with Go
Use SQLite from Go the way production code does: one *sql.DB, pragmas in the DSN, WAL and immediate transactions, STRICT tables, UPSERT, JSON, FTS5 and migrations. Every example is a complete program that runs with go run against the pure-Go modernc.org/sqlite driver. GopherForge 1.3.5 adds a SQLite project template whose Go program uses database/sql through the app's bundled gopherforge.app/sqlite driver (registered as sqlite, backed by the system SQLite on iPhone and iPad); databases a program writes under /sandbox are kept with the project; and a database browser per project with tables, schema, rows and a SQL console, plus import and export of .sqlite/.db files through Files.
Start with “Open a SQLite database from Go: database/sql, a driver and a file” →
Who it is for
Go developers who want an embedded database for a CLI, a desktop or mobile app, a small web service or fast integration tests, and who want to know where SQLite behaves differently from a database server.
Before you start
Basic Go: structs, errors, interfaces and goroutines. Basic SQL (SELECT, INSERT, JOIN) helps; no SQLite experience is needed.
What you will be able to do
- Open SQLite through database/sql, choose between modernc.org/sqlite, mattn/go-sqlite3 and ncruces/go-sqlite3, and configure every pooled connection through the DSN.
- Explain type affinity, STRICT tables, rowid keys, NULL handling and time storage, and enforce foreign keys on every connection.
- Write transactions with RETURNING and UPSERT, run WAL with busy_timeout, and avoid SQLITE_BUSY_SNAPSHOT with BEGIN IMMEDIATE and a single writer.
- Query JSON, rank full-text search with FTS5, use window functions and CTEs, and read EXPLAIN QUERY PLAN to add the right indexes.
- Migrate with PRAGMA user_version, back up with VACUUM INTO, test against temporary databases and ship a tested notes repository.
Unit 1. SQLite from Go: connections, drivers and types
database/sql and lazy opens, drivers and DSN pragmas, :memory: and the pool, type affinity and STRICT tables, rowid keys, NULLs, time values and foreign keys.
Open a SQLite database from Go: database/sql, a driver and a file
Open a file database through database/sql, see that sql.Open connects lazily, and run Exec, Query and QueryRow with placeholders and complete error handling.
5 min · Worked lesson
Choose a SQLite driver and configure every connection through the DSN
Compare modernc.org/sqlite, mattn/go-sqlite3 and ncruces/go-sqlite3, and use DSN parameters so that every pooled connection gets the same pragmas and transaction mode.
4 min · Worked lesson
:memory: is per connection: the pool, SetMaxOpenConns(1), memdb and shared cache
Explain why an in-memory database vanishes between pooled connections and choose between a single connection, the memdb VFS, shared cache and a temporary file.
3 min · Worked lesson
Type affinity, dynamic typing and STRICT tables
Predict the storage class SQLite gives each value from a column's declared type, see what Go receives when scanning into any, and use STRICT tables to reject values that do not fit.
3 min · Worked lesson
INTEGER PRIMARY KEY, rowid, AUTOINCREMENT and WITHOUT ROWID
Recognize when a primary key is an alias for the rowid, decide whether AUTOINCREMENT is worth its cost, and know when a WITHOUT ROWID table fits.
4 min · Worked lesson
NULLs and time values: sql.Null, pointers, COALESCE and a time format you choose
Scan nullable columns with sql.NullString, sql.Null[T] and pointers, write NULL-aware SQL, and store times in a format that sorts and that SQLite's date functions understand.
3 min · Worked lesson
Foreign keys are off until each connection turns them on
Show that REFERENCES clauses are not enforced by default, enable enforcement for every connection through the DSN, use ON DELETE CASCADE and find existing violations with foreign_key_check.
3 min · Worked lesson
Unit 2. Transactions, concurrency and queries
Transactions and RETURNING, UPSERT, WAL and busy_timeout, BEGIN IMMEDIATE, JSON functions, window functions and CTEs, and query plans.
Transactions and RETURNING: all-or-nothing changes that hand back what they wrote
Group related writes in a database/sql transaction that always rolls back on failure, read generated values with RETURNING, and classify a constraint failure by its extended SQLite result code.
4 min · Worked lesson
UPSERT with ON CONFLICT: counters, insert-if-absent and why INSERT OR REPLACE deletes rows
Write ON CONFLICT DO UPDATE and DO NOTHING statements that use excluded values and RETURNING, and explain why INSERT OR REPLACE changes rowids and fires cascading deletes.
4 min · Worked lesson
WAL mode, synchronous and busy_timeout: readers that never wait and writers that queue
Switch a database to write-ahead logging, explain which settings persist in the file and which are per connection, and turn SQLITE_BUSY into a bounded wait with busy_timeout.
4 min · Worked lesson
BEGIN IMMEDIATE and one writer: avoid SQLITE_BUSY_SNAPSHOT that no timeout can fix
Explain why a deferred transaction that reads and then writes can fail with SQLITE_BUSY_SNAPSHOT regardless of busy_timeout, and prevent it with BEGIN IMMEDIATE through _txlock and a single-writer pool.
4 min · Worked lesson
JSON in SQLite: json_extract, -> and ->>, json_each and indexed generated columns
Store JSON documents with a validity check, query paths with json_extract, -> and ->>, expand arrays with json_each and index a field through a generated column.
4 min · Worked lesson
Window functions and CTEs: running totals, top N per group and recursive queries
Compute running totals, differences and shares with window functions, select the top rows per group with row_number, and walk series and trees with recursive common table expressions.
4 min · Worked lesson
Read EXPLAIN QUERY PLAN: SCAN, SEARCH, covering indexes, sorts and ANALYZE
Read EXPLAIN QUERY PLAN output from Go, add indexes that turn scans into searches and remove temporary sorts, use expression indexes for computed filters, and keep statistics fresh with ANALYZE and PRAGMA optimize.
5 min · Worked lesson
Unit 3. SQLite project: a tested notes repository
Migrations with user_version, FTS5 search, backups and maintenance, tests with temporary databases, and a complete notes repository.
Migrate a schema with PRAGMA user_version: ordered steps, one transaction each
Apply append-only migrations that record their version in PRAGMA user_version inside the same transaction, skip applied steps, roll back a failing step and refuse a newer schema.
4 min · Worked lesson
Full-text search with FTS5: an external-content index, ranking and safe queries
Index a table with an external-content FTS5 table kept in sync by triggers, query it with prefixes, phrases, operators and column filters, rank with bm25, and quote user input.
4 min · Worked lesson
Back up and maintain a live database: VACUUM INTO, checkpoints, VACUUM and ANALYZE
Take a consistent backup of a WAL database with VACUUM INTO, verify the copy, reclaim free pages, truncate the WAL with a checkpoint and keep planner statistics current.
4 min · Worked lesson
Test against real SQLite: a fresh migrated database file per test
Write a test helper that opens a migrated file database in t.TempDir, registers cleanup, and lets table-driven and parallel tests run against isolated databases.
4 min · Worked lesson
Project: a tested notes repository with migrations, transactions and full-text search
Build a small notes store on SQLite that migrates itself, writes in IMMEDIATE transactions with RETURNING and optimistic versions, cascades tags, and searches with FTS5, with a check for every behaviour.
5 min · Worked lesson
Related: Around Go: SQL services · Around Go: MongoDB and Redis · Web application security