SQLite from Go: connections, drivers and types · 4 MIN READ
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.
Almost every SQLite table is a B-tree keyed by a hidden 64-bit integer, the rowid. Declaring a column exactly INTEGER PRIMARY KEY makes it that key, which is fast and is what LastInsertId returns. A small spelling difference, INT instead of INTEGER, gives you a second, separate key, and AUTOINCREMENT changes how ids are reused at a cost most tables do not need.
sqlite · A MAP OF THE IDEA
- Integer surrogate key?
- INTEGER PRIMARY KEY
- Ids leak? AUTOINCREMENT
- Composite: WITHOUT ROWID
Useful when
- The rowid alias makes key lookups a single B-tree search.
- RETURNING reports keys for any table shape.
Watch out
- INT PRIMARY KEY silently adds a second key.
- AUTOINCREMENT costs a write and is still not gapless.
Implementation & operation cost: Choosing the key declaration deliberately per table; changing it later means rebuilding the table.
The rowid and its alias
A column declared with the type INTEGER and PRIMARY KEY becomes an alias for the rowid: the value is the B-tree key, lookups by it need no separate index, and inserting without a value picks one for you. Any other primary key, including INT PRIMARY KEY, BIGINT PRIMARY KEY or a composite key, is an ordinary unique index next to the hidden rowid. Without AUTOINCREMENT the new rowid is normally one more than the largest rowid in the table, so after deleting the newest row its id can be handed out again.
Four tables side by side
The program creates a table with INTEGER PRIMARY KEY, one with AUTOINCREMENT, one with INT PRIMARY KEY and a WITHOUT ROWID table with a composite key. It deletes the newest row and inserts again, inspects sqlite_sequence, inserts explicit ids, and uses RETURNING to read back a composite key that LastInsertId cannot describe.
package main
import (
"context"
"database/sql"
"fmt"
"log"
_ "modernc.org/sqlite"
)
var ctx = context.Background()
func must(db *sql.DB, query string, args ...any) sql.Result {
res, err := db.ExecContext(ctx, query, args...)
if err != nil {
log.Fatal(err)
}
return res
}
func list(db *sql.DB, query string) string {
var s sql.NullString
if err := db.QueryRowContext(ctx, query).Scan(&s); err != nil {
log.Fatal(err)
}
return s.String
}
func main() {
db, err := sql.Open("sqlite", ":memory:")
if err != nil {
log.Fatal(err)
}
defer db.Close()
db.SetMaxOpenConns(1)
must(db, `
CREATE TABLE plain (id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE counted (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT);
CREATE TABLE intkey (id INT PRIMARY KEY, name TEXT);
CREATE TABLE members (team TEXT, user TEXT, role TEXT, PRIMARY KEY (team, user)) WITHOUT ROWID;`)
// INTEGER PRIMARY KEY is the rowid: id and rowid are the same column.
for _, table := range []string{"plain", "counted"} {
for _, name := range []string{"ada", "brian", "carol"} {
must(db, "INSERT INTO "+table+" (name) VALUES (?)", name)
}
must(db, "DELETE FROM "+table+" WHERE id = 3")
res := must(db, "INSERT INTO "+table+" (name) VALUES ('dave')")
id, _ := res.LastInsertId()
fmt.Printf("%-8s after deleting id 3, the next insert gets id %d; rows: %s\n",
table, id, list(db, "SELECT group_concat(id || '=' || name, ' ') FROM "+table))
}
fmt.Println("sqlite_sequence:", list(db, "SELECT group_concat(name || '=' || seq) FROM sqlite_sequence"))
fmt.Println("plain: id equals rowid for every row:",
list(db, "SELECT CASE WHEN count(*) = sum(id = rowid) THEN 'true' ELSE 'false' END FROM plain"))
// INT PRIMARY KEY is not an alias: the table has a separate hidden rowid.
must(db, "INSERT INTO intkey (id, name) VALUES (100, 'eve'), (200, 'frank')")
fmt.Println("INT PRIMARY KEY (id:rowid):", list(db, "SELECT group_concat(id || ':' || rowid, ' ') FROM intkey"))
// An explicit id is accepted; without AUTOINCREMENT the next one is max(rowid)+1.
must(db, "INSERT INTO plain (id, name) VALUES (1000, 'grace')")
res := must(db, "INSERT INTO plain (name) VALUES ('heidi')")
id, _ := res.LastInsertId()
fmt.Println("plain after an explicit id 1000, next id:", id)
// RETURNING reports the key directly, also for WITHOUT ROWID tables.
var team, user string
if err := db.QueryRowContext(ctx,
"INSERT INTO members (team, user, role) VALUES ('core', 'ada', 'owner') RETURNING team, user").Scan(&team, &user); err != nil {
log.Fatal(err)
}
fmt.Printf("WITHOUT ROWID key: (%s, %s)\n", team, user)
_, err = db.ExecContext(ctx, "INSERT INTO members (team, user, role) VALUES ('core', 'ada', 'viewer')")
fmt.Println("duplicate composite key:", err)
fmt.Println("tables without rowid:", list(db, "SELECT group_concat(name) FROM pragma_table_list WHERE wr = 1"))
}In plain, deleting id 3 and inserting again reuses 3; in counted, AUTOINCREMENT remembers 3 in sqlite_sequence and hands out 4. id equals rowid for every row of plain. The INT PRIMARY KEY table stores ids 100 and 200 with hidden rowids 1 and 2. After an explicit id 1000 the next automatic id is 1001. The WITHOUT ROWID insert returns its key through RETURNING, a duplicate key fails with extended code 1555 (SQLITE_CONSTRAINT_PRIMARYKEY), and pragma_table_list marks members as a WITHOUT ROWID table.
When AUTOINCREMENT is worth it
AUTOINCREMENT guarantees that an id is never reused, even after the row with the largest id is deleted. It does so by keeping the high-water mark in the internal sqlite_sequence table and updating it on every insert, which costs extra work and an extra write. Use it when ids escape into the world and reuse would be a bug: an id printed on an invoice, cached by clients or referenced by another system that might not see the delete. For internal keys that only appear in foreign keys with ON DELETE handling, plain INTEGER PRIMARY KEY is enough and faster. Neither variant promises gapless ids; a rolled-back insert still consumes an AUTOINCREMENT value.
WITHOUT ROWID tables
A WITHOUT ROWID table stores rows in a B-tree keyed by its declared primary key, so a lookup by that key reads one tree instead of an index and then the table. It suits tables with a non-integer or composite primary key and small rows, such as memberships, tag links and key-value settings. It requires a PRIMARY KEY, does not support AUTOINCREMENT, and LastInsertId has no meaning for it, so use RETURNING or the key you inserted. With large rows, an ordinary rowid table is usually better. Do not use it for an INTEGER PRIMARY KEY table: that is already keyed by the rowid.
Ids in Go
Result.LastInsertId returns the rowid of the most recent successful insert on the connection that ran your statement, which database/sql hands back with the Result; it is reliable for single-row inserts into rowid tables. For multi-row inserts, upserts or WITHOUT ROWID tables, prefer INSERT ... RETURNING id, which reports exactly the rows the statement wrote. Scan rowids into int64: they are signed 64-bit integers, and if the largest possible rowid is ever in use, a table without AUTOINCREMENT gets a randomly chosen unused rowid while an AUTOINCREMENT table fails with SQLITE_FULL.
TAKE THIS WITH YOU
Spell integer keys exactly INTEGER PRIMARY KEY to get the rowid alias. Add AUTOINCREMENT only when an id must never be reused, use WITHOUT ROWID for small rows with composite or text keys, and read generated keys with RETURNING when LastInsertId cannot describe them.
Check your understanding
A table uses id INTEGER PRIMARY KEY without AUTOINCREMENT. You delete the row with the largest id and insert a new row. Which id can it receive?
Go to the source
Progress stays in this browser. No account needed.