SQLite
suggest changeSQLite is an embedded SQL database: the whole database lives in one file, and the engine runs inside your process. No server to install, no network round-trips. It's a great fit for command-line tools, desktop apps, tests, caches and plenty of web apps.
In Go you use SQLite through the standard database/sql package plus a driver. See SQL for the general database/sql API. This article covers what's specific to SQLite.
Choosing a driver
There are three popular drivers:
| Driver | Driver name | Notes |
|---|---|---|
| modernc.org/sqlite | "sqlite" |
SQLite's C code machine-translated to Go. No cgo, cross-compiles easily. |
| github.com/mattn/go-sqlite3 | "sqlite3" |
Wraps the C library with cgo. Needs a C compiler (CGO_ENABLED=1). The oldest and most widely used. |
| github.com/ncruces/go-sqlite3 | "sqlite3" |
SQLite compiled to WebAssembly, run with wazero. No cgo. |
The examples here use modernc.org/sqlite because it builds with a plain go build on every platform:
go get modernc.org/sqlite
The SQL and the database/sql code are the same for every driver. What differs is the driver name, the import and how connection options are written in the data source name (DSN).
Opening a database
package main
import (
"database/sql"
"fmt"
"log"
_ "modernc.org/sqlite"
)
func main() {
db, err := sql.Open("sqlite", "books.db")
if err != nil {
log.Fatal(err)
}
defer db.Close()
// sql.Open doesn't touch the file; Ping opens a connection.
if err := db.Ping(); err != nil {
log.Fatal(err)
}
var version string
err = db.QueryRow("SELECT sqlite_version()").Scan(&version)
if err != nil {
log.Fatal(err)
}
fmt.Println("SQLite version:", version)
}
SQLite version: 3.53.4
The blank import _ "modernc.org/sqlite" registers the driver under the name "sqlite". The file books.db is created if it doesn't exist.
The DSN can be a plain file name or a file: URI with query parameters. modernc.org/sqlite supports:
_pragma=name(value)runsPRAGMA name = valueon every new connection. Repeat it for multiple pragmas._txlock=immediatemakesBeginissueBEGIN IMMEDIATEinstead ofBEGIN(more on this below)._time_format=sqlitecontrols howtime.Timevalues are written.- standard SQLite URI parameters such as
mode=ro(read-only) ormode=memory.
dsn := "file:app.db?_pragma=foreign_keys(1)&_pragma=journal_mode(WAL)&_pragma=busy_timeout(5000)"
db, err := sql.Open("sqlite", dsn)
Why put pragmas in the DSN instead of calling db.Exec("PRAGMA foreign_keys = ON")? Most pragmas apply to a single connection, and *sql.DB is a pool that opens new connections whenever it needs them. A pragma you Exec once runs on one random connection only. DSN pragmas run on every connection.
The equivalent DSN for mattn/go-sqlite3 uses different parameter names:
dsn := "file:app.db?_foreign_keys=on&_journal_mode=WAL&_busy_timeout=5000&_txlock=immediate"
db, err := sql.Open("sqlite3", dsn)
Create, insert, query
package main
import (
"database/sql"
"errors"
"fmt"
"log"
"os"
_ "modernc.org/sqlite"
)
const schema = `
CREATE TABLE IF NOT EXISTS books (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
author TEXT NOT NULL,
year INTEGER,
isbn TEXT UNIQUE
);`
type Book struct {
ID int64
Title string
Author string
Year sql.NullInt64
ISBN sql.Null[string]
}
func main() {
os.Remove("books.db") // start fresh for the demo
db, err := sql.Open("sqlite", "file:books.db?_pragma=foreign_keys(1)")
if err != nil {
log.Fatal(err)
}
defer db.Close()
if _, err := db.Exec(schema); err != nil {
log.Fatal(err)
}
res, err := db.Exec(
"INSERT INTO books (title, author, year, isbn) VALUES (?, ?, ?, ?)",
"The Go Programming Language", "Donovan & Kernighan", 2015, "978-0134190440")
if err != nil {
log.Fatal(err)
}
id, _ := res.LastInsertId()
fmt.Println("inserted id:", id)
// a nil argument is stored as NULL
_, err = db.Exec(
"INSERT INTO books (title, author, year, isbn) VALUES (?, ?, ?, ?)",
"Concurrency in Go", "Katherine Cox-Buday", 2017, nil)
if err != nil {
log.Fatal(err)
}
// named parameters
_, err = db.Exec(
"INSERT INTO books (title, author) VALUES (:title, :author)",
sql.Named("title", "Untitled draft"), sql.Named("author", "Anonymous"))
if err != nil {
log.Fatal(err)
}
rows, err := db.Query("SELECT id, title, author, year, isbn FROM books ORDER BY id")
if err != nil {
log.Fatal(err)
}
defer rows.Close()
for rows.Next() {
var b Book
if err := rows.Scan(&b.ID, &b.Title, &b.Author, &b.Year, &b.ISBN); err != nil {
log.Fatal(err)
}
year := "unknown"
if b.Year.Valid {
year = fmt.Sprint(b.Year.Int64)
}
isbn := "-"
if b.ISBN.Valid {
isbn = b.ISBN.V
}
fmt.Printf("%d | %-28s | %-20s | %-7s | %s\n", b.ID, b.Title, b.Author, year, isbn)
}
if err := rows.Err(); err != nil {
log.Fatal(err)
}
var title string
err = db.QueryRow("SELECT title FROM books WHERE id = ?", 42).Scan(&title)
if errors.Is(err, sql.ErrNoRows) {
fmt.Println("book 42 not found")
} else if err != nil {
log.Fatal(err)
}
res, err = db.Exec("UPDATE books SET year = ? WHERE year IS NULL", 2026)
if err != nil {
log.Fatal(err)
}
n, _ := res.RowsAffected()
fmt.Println("updated rows:", n)
}
inserted id: 1
1 | The Go Programming Language | Donovan & Kernighan | 2015 | 978-0134190440
2 | Concurrency in Go | Katherine Cox-Buday | 2017 | -
3 | Untitled draft | Anonymous | unknown | -
book 42 not found
updated rows: 1
Notes:
- Always pass values as
?(or:name,$name,@name) parameters. Never build SQL withfmt.Sprintffrom user input, that's how SQL injection happens. - A column declared
INTEGER PRIMARY KEYis an alias for SQLite'srowid. It's filled in automatically andLastInsertIdreturns it. - Scanning
NULLinto a plainint64orstringfails. Usesql.NullInt64,sql.NullStringand friends, or the genericsql.Null[T](Go 1.22+). A pointer such as*stringworks too, it'snilforNULL. QueryRowreturnssql.ErrNoRowsfromScanwhen there's no result. Check it witherrors.Is.- Always
rows.Close()and checkrows.Err()after the loop. An unclosedRowskeeps a connection busy.
SQLite types are flexible
SQLite has only five storage classes: NULL, INTEGER, REAL, TEXT and BLOB. A column's declared type is only a preference ("type affinity"). By default you can store a string in an INTEGER column and SQLite won't complain.
If you want strict checking, add STRICT to the table definition (SQLite 3.37+):
CREATE TABLE books (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
year INTEGER
) STRICT;
In a STRICT table only INT, INTEGER, REAL, TEXT, BLOB and ANY are allowed as column types, and inserting 'abc' into year returns an error.
There's no boolean type: true and false are stored as integers 1 and 0, and scanning back into a bool works.
There's also no date/time type, which leads to the next section.
Dates and times
SQLite stores timestamps as text, a real number (Julian day) or an integer (Unix time). Its built-in date functions understand text in the form YYYY-MM-DD HH:MM:SS.
By default modernc.org/sqlite writes a time.Time using Go's time.Time.String() format, which looks like 2026-10-17 19:24:51.9465587 +0200 CEST m=+0.904186901. That includes a monotonic clock reading and a time zone name, and SQLite's date() functions can't parse it. Add _time_format=sqlite to the DSN to get the SQLite-friendly format:
package main
import (
"database/sql"
"fmt"
"log"
"time"
_ "modernc.org/sqlite"
)
func main() {
db, err := sql.Open("sqlite", "file:times.db?_time_format=sqlite")
if err != nil {
log.Fatal(err)
}
defer db.Close()
db.Exec("DROP TABLE IF EXISTS t")
db.Exec("CREATE TABLE t (created DATETIME)")
when := time.Date(2026, 10, 17, 9, 30, 0, 0, time.UTC)
db.Exec("INSERT INTO t VALUES (?)", when)
db.Exec("INSERT INTO t VALUES (?)", time.Now().UTC())
var raw string
db.QueryRow("SELECT CAST(created AS TEXT) FROM t LIMIT 1").Scan(&raw)
fmt.Println("stored as:", raw)
var got time.Time
db.QueryRow("SELECT created FROM t LIMIT 1").Scan(&got)
fmt.Println("scanned: ", got, got.Equal(when))
var n int
db.QueryRow("SELECT count(*) FROM t WHERE created >= ?", when).Scan(&n)
fmt.Println("rows since:", n)
var d string
db.QueryRow("SELECT date(created) FROM t LIMIT 1").Scan(&d)
fmt.Println("date():", d)
}
stored as: 2026-10-17 09:30:00+00:00
scanned: 2026-10-17 09:30:00 +0000 +0000 true
rows since: 2
date(): 2026-10-17
Two rules that avoid most time bugs:
- Store times in UTC (
t.UTC()). Text comparisons such ascreated >= ?only sort correctly when every value uses the same offset. - Declare the column as
DATETIME,DATEorTIMESTAMP. The driver uses the declared type to decide whether to parse the text back into atime.Timewhen you scan.
If you prefer, store Unix time as an INTEGER (t.Unix() or t.UnixMilli()) and convert with time.Unix when reading. It's compact, unambiguous and works the same with every driver.
Transactions and bulk inserts
Each statement executed outside a transaction is its own transaction, and committing a transaction means waiting for the data to reach the disk. That makes many individual inserts slow. Wrap them in one transaction and reuse a prepared statement:
package main
import (
"context"
"database/sql"
"fmt"
"log"
"os"
"time"
_ "modernc.org/sqlite"
)
func insertMany(ctx context.Context, db *sql.DB, n int) error {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback() // no-op after a successful Commit
stmt, err := tx.PrepareContext(ctx, "INSERT INTO events (name, created) VALUES (?, ?)")
if err != nil {
return err
}
defer stmt.Close()
for i := range n {
_, err := stmt.ExecContext(ctx, fmt.Sprintf("event-%d", i), time.Now().UTC())
if err != nil {
return err
}
}
return tx.Commit()
}
func main() {
os.Remove("events.db")
db, err := sql.Open("sqlite", "file:events.db?_time_format=sqlite")
if err != nil {
log.Fatal(err)
}
defer db.Close()
ctx := context.Background()
_, err = db.ExecContext(ctx, `CREATE TABLE events (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL UNIQUE,
created DATETIME NOT NULL
)`)
if err != nil {
log.Fatal(err)
}
start := time.Now()
for i := range 200 {
_, err := db.ExecContext(ctx, "INSERT INTO events (name, created) VALUES (?, ?)",
fmt.Sprintf("slow-%d", i), time.Now().UTC())
if err != nil {
log.Fatal(err)
}
}
fmt.Printf("200 inserts without a transaction: %v\n", time.Since(start).Round(time.Millisecond))
start = time.Now()
if err := insertMany(ctx, db, 10000); err != nil {
log.Fatal(err)
}
fmt.Printf("10000 inserts in one transaction: %v\n", time.Since(start).Round(time.Millisecond))
}
200 inserts without a transaction: 894ms
10000 inserts in one transaction: 29ms
Exact numbers depend on your disk, but a 1000x difference per row is typical.
The defer tx.Rollback() pattern is idiomatic: if any step returns early with an error, the transaction is rolled back; after Commit succeeds, Rollback does nothing and returns sql.ErrTxDone, which we ignore.
Inspecting errors
modernc.org/sqlite returns errors of type *sqlite.Error with the SQLite result code. The constants are in modernc.org/sqlite/lib. A common use is detecting a duplicate key:
import (
"errors"
"modernc.org/sqlite"
sqlite3 "modernc.org/sqlite/lib"
)
func isUniqueViolation(err error) bool {
var serr *sqlite.Error
return errors.As(err, &serr) && serr.Code() == sqlite3.SQLITE_CONSTRAINT_UNIQUE
}
Inserting event-1 a second time into the table above returns:
constraint failed: UNIQUE constraint failed: events.name (2067)
and isUniqueViolation returns true. With mattn/go-sqlite3 the type is sqlite3.Error (a value, not a pointer) with fields Code and ExtendedCode, e.g. sqliteErr.ExtendedCode == sqlite3.ErrConstraintUnique.
Often you don't need to inspect the error at all because SQL can handle the conflict, see UPSERT below.
UPSERT and RETURNING
SQLite supports INSERT ... ON CONFLICT DO UPDATE (upsert) and RETURNING, so you can insert-or-update and read the result in one statement. Because RETURNING produces rows, run it with QueryRow, not Exec:
func hit(db *sql.DB, url string) (int, error) {
var hits int
err := db.QueryRow(`
INSERT INTO pages (url, hits) VALUES (?, 1)
ON CONFLICT (url) DO UPDATE SET hits = hits + 1
RETURNING hits`, url).Scan(&hits)
return hits, err
}
Calling it for /, /about, /, / prints:
/ hits=1
/about hits=1
/ hits=2
/ hits=3
Concurrency: WAL, busy timeout and locking
SQLite allows many readers but only one writer at a time, for the whole database. When a second connection tries to write while another holds the lock, it gets SQLITE_BUSY ("database is locked"). Since *sql.DB is a pool of connections, a Go program that writes from several goroutines hits this quickly with default settings.
This program runs 20 goroutines, each doing 50 small write transactions:
package main
import (
"database/sql"
"fmt"
"log"
"os"
"sync"
_ "modernc.org/sqlite"
)
func run(dsn string) {
for _, f := range []string{"app.db", "app.db-wal", "app.db-shm"} {
os.Remove(f)
}
db, err := sql.Open("sqlite", dsn)
if err != nil {
log.Fatal(err)
}
defer db.Close()
if _, err := db.Exec("CREATE TABLE counter (n INTEGER)"); err != nil {
log.Fatal(err)
}
var wg sync.WaitGroup
var mu sync.Mutex
failures := 0
for range 20 {
wg.Go(func() {
for range 50 {
tx, err := db.Begin()
if err == nil {
_, err = tx.Exec("INSERT INTO counter VALUES (1)")
if err == nil {
err = tx.Commit()
} else {
tx.Rollback()
}
}
if err != nil {
mu.Lock()
if failures == 0 {
fmt.Println(" first error:", err)
}
failures++
mu.Unlock()
}
}
})
}
wg.Wait()
var n int
db.QueryRow("SELECT count(*) FROM counter").Scan(&n)
var mode string
db.QueryRow("PRAGMA journal_mode").Scan(&mode)
fmt.Printf(" journal_mode=%s rows=%d failures=%d\n", mode, n, failures)
}
func main() {
fmt.Println("defaults:")
run("app.db")
fmt.Println("WAL + busy_timeout + immediate:")
run("file:app.db?_pragma=journal_mode(WAL)&_pragma=busy_timeout(5000)&_txlock=immediate")
}
defaults:
first error: database is locked (5) (SQLITE_BUSY)
journal_mode=delete rows=20 failures=980
WAL + busy_timeout + immediate:
journal_mode=wal rows=1000 failures=0
With defaults almost all writes failed (the exact count varies from run to run). Three settings fix it:
journal_mode(WAL)switches to write-ahead logging. Readers no longer block the writer and the writer no longer blocks readers. It's persistent: once set, the database file stays in WAL mode. You'll seeapp.db-walandapp.db-shmfiles next to the database; they're part of it, so copy all three (or useVACUUM INTO 'backup.db'to make a single-file copy).busy_timeout(5000)makes a connection wait up to 5 seconds for the lock instead of failing immediately._txlock=immediatestarts transactions withBEGIN IMMEDIATE, which takes the write lock up front. A plainBEGINstarts as a reader and tries to upgrade to a writer on the first write. If another connection wrote in the meantime, the upgrade fails withSQLITE_BUSYright away, andbusy_timeoutcan't help. For read-only transactions use a separate read-only pool (see below) so they don't take the write lock.
A common setup for a server is two pools: one for writes limited to a single connection, so writers queue inside Go instead of fighting over the lock, and one for reads with many connections:
func openDB(path string) (writeDB, readDB *sql.DB, err error) {
const opts = "_pragma=journal_mode(WAL)&_pragma=busy_timeout(5000)" +
"&_pragma=foreign_keys(1)&_pragma=synchronous(NORMAL)&_time_format=sqlite"
writeDB, err = sql.Open("sqlite", "file:"+path+"?"+opts+"&_txlock=immediate")
if err != nil {
return nil, nil, err
}
writeDB.SetMaxOpenConns(1)
readDB, err = sql.Open("sqlite", "file:"+path+"?"+opts+"&mode=ro")
if err != nil {
writeDB.Close()
return nil, nil, err
}
readDB.SetMaxOpenConns(max(4, runtime.NumCPU()))
return writeDB, readDB, nil
}
synchronous(NORMAL) is safe in WAL mode (the database can't be corrupted) and makes commits much faster; a power loss can only lose the last few transactions.
In-memory databases
The special name :memory: creates a database that lives in RAM and disappears when closed. It's handy for tests, but there's a catch: every connection gets its own separate in-memory database, and *sql.DB may open several connections.
db, _ := sql.Open("sqlite", ":memory:")
db.Exec("CREATE TABLE t (x)")
ctx := context.Background()
c1, _ := db.Conn(ctx)
_, err := c1.ExecContext(ctx, "SELECT * FROM t")
fmt.Println("conn1:", err)
c2, _ := db.Conn(ctx)
_, err = c2.ExecContext(ctx, "SELECT * FROM t")
fmt.Println("conn2:", err)
conn1: <nil>
conn2: SQL logic error: no such table: t (1)
The second connection sees an empty database. The simple fix is to limit the pool to one connection, which also keeps the database alive as long as db is open:
db, err := sql.Open("sqlite", ":memory:")
if err != nil {
log.Fatal(err)
}
db.SetMaxOpenConns(1)
For tests that need real concurrency, use a temporary file instead: filepath.Join(t.TempDir(), "test.db").
Schema migrations with user_version
SQLite has a free integer slot in the database header, PRAGMA user_version, meant for exactly this. Store your migrations in a slice and apply the ones newer than the stored version:
package main
import (
"database/sql"
"fmt"
"log"
_ "modernc.org/sqlite"
)
var migrations = []string{
// version 1
`CREATE TABLE pages (
url TEXT PRIMARY KEY,
hits INTEGER NOT NULL DEFAULT 0
)`,
// version 2
`ALTER TABLE pages ADD COLUMN meta TEXT`,
}
func migrate(db *sql.DB) error {
var version int
if err := db.QueryRow("PRAGMA user_version").Scan(&version); err != nil {
return err
}
for i := version; i < len(migrations); i++ {
tx, err := db.Begin()
if err != nil {
return err
}
if _, err := tx.Exec(migrations[i]); err != nil {
tx.Rollback()
return fmt.Errorf("migration %d: %w", i+1, err)
}
// PRAGMA doesn't accept ? parameters
if _, err := tx.Exec(fmt.Sprintf("PRAGMA user_version = %d", i+1)); err != nil {
tx.Rollback()
return err
}
if err := tx.Commit(); err != nil {
return err
}
fmt.Println("applied migration", i+1)
}
return nil
}
func main() {
db, err := sql.Open("sqlite", ":memory:")
if err != nil {
log.Fatal(err)
}
defer db.Close()
db.SetMaxOpenConns(1)
if err := migrate(db); err != nil {
log.Fatal(err)
}
if err := migrate(db); err != nil { // second run is a no-op
log.Fatal(err)
}
db.Exec(`INSERT INTO pages (url, meta) VALUES (?, ?)`,
"/", `{"title":"Home","tags":["go","sqlite"]}`)
var title string
var tags int
err = db.QueryRow(`SELECT meta->>'$.title', json_array_length(meta, '$.tags')
FROM pages WHERE url = ?`, "/").Scan(&title, &tags)
if err != nil {
log.Fatal(err)
}
fmt.Println("title:", title, "tags:", tags)
}
applied migration 1
applied migration 2
title: Home tags: 2
Unlike most databases, SQLite runs DDL statements (CREATE, ALTER) inside transactions, so a failed migration leaves the schema untouched.
The example also shows SQLite's built-in JSON support: store JSON as TEXT and query it with ->>, json_extract, json_array_length and friends. That's often enough to avoid a separate document store.
For larger projects, you can keep migrations as .sql files and include them in the binary with //go:embed, or use a migration tool such as goose or golang-migrate, both of which support SQLite.
Summary
- Use
modernc.org/sqlite(driver"sqlite") for a cgo-free build ormattn/go-sqlite3(driver"sqlite3") for the C library. - Set per-connection pragmas in the DSN, not with a one-off
Exec. - Turn on
foreign_keys; SQLite doesn't enforce foreign keys by default. - For concurrent writes use WAL mode,
busy_timeoutandBEGIN IMMEDIATE, and consider a single-connection write pool. - Batch writes in transactions.
- Store times in UTC and use
_time_format=sqlite(or Unix integers). - With
:memory:calldb.SetMaxOpenConns(1).