Transactions, concurrency and queries · 4 MIN READ
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.
SQLite has no separate JSON column type, but its JSON functions, built into the core library since 3.38, read and edit JSON stored as TEXT. That makes it practical to keep a flexible payload next to ordinary columns: validate it on write, query into it with path expressions, and promote the fields you filter on into generated columns that can be indexed like any other.
sqlite · A MAP OF THE IDEA
- TEXT with json_valid
- ->> for scalar values
- json_each for arrays
- Index generated columns
Useful when
- Flexible payloads without a migration per optional field.
- Hot paths become indexed columns without duplicating data.
Watch out
- Constraints apply to columns, not to fields inside a document.
- -> returns JSON text, so comparisons with strings can surprise.
Implementation & operation cost: Parsing on every unindexed read; one generated column and index per field you filter on.
Three ways to read a path
json_extract(doc, '$.user.plan') returns an SQL value: text for a JSON string, integer or real for a number, and JSON text for an object or array. The -> operator, added in 3.38 with syntax borrowed from PostgreSQL and MySQL, always returns JSON text, so a string comes back with its quotes. ->> returns an SQL value like json_extract. Use ->> or json_extract when you compare or display a scalar, and -> when you pass a fragment on to another JSON function. Paths start at $, use .key for members and [n] for array elements, and [#-1] counts from the end.
Events with a JSON payload
The program stores events as JSON text with CHECK (json_valid(doc)), so malformed documents are rejected at write time. A VIRTUAL generated column, kind, is defined as doc ->> '$.kind' and indexed. It then reads one document three ways, groups by a path, expands the tags array with json_each, asks the planner how it finds a kind, decodes a document into a Go struct and edits one in SQL with json_set.
package main
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"log"
"os"
"path/filepath"
_ "modernc.org/sqlite"
)
type Event struct {
Kind string `json:"kind"`
User struct {
ID int `json:"id"`
Plan string `json:"plan"`
} `json:"user"`
Tags []string `json:"tags"`
}
func main() {
ctx := context.Background()
dir, err := os.MkdirTemp("", "json")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(dir)
db, err := sql.Open("sqlite", filepath.Join(dir, "app.db"))
if err != nil {
log.Fatal(err)
}
defer db.Close()
if _, err := db.ExecContext(ctx, `CREATE TABLE events (
id INTEGER PRIMARY KEY,
doc TEXT NOT NULL CHECK (json_valid(doc)),
kind TEXT GENERATED ALWAYS AS (doc ->> '$.kind') VIRTUAL
);
CREATE INDEX events_kind ON events (kind)`); err != nil {
log.Fatal(err)
}
docs := []string{
`{"kind":"signup","user":{"id":7,"plan":"free"},"tags":["web","eu"]}`,
`{"kind":"upgrade","user":{"id":7,"plan":"pro"},"tags":["web"]}`,
`{"kind":"signup","user":{"id":9,"plan":"free"},"tags":["ios"]}`,
}
for _, d := range docs {
if _, err := db.ExecContext(ctx, "INSERT INTO events (doc) VALUES (?)", d); err != nil {
log.Fatal(err)
}
}
_, err = db.ExecContext(ctx, "INSERT INTO events (doc) VALUES (?)", `{"kind":`)
fmt.Println("invalid JSON rejected:", err != nil)
// -> returns JSON text, ->> returns an SQL value; json_extract returns an SQL value too.
var arrow, arrow2, extract string
var arrowType, arrow2Type string
if err := db.QueryRowContext(ctx, `SELECT doc -> '$.user.plan', typeof(doc -> '$.user.id'),
doc ->> '$.user.plan', typeof(doc ->> '$.user.id'), json_extract(doc, '$.tags[0]')
FROM events WHERE id = 1`).Scan(&arrow, &arrowType, &arrow2, &arrow2Type, &extract); err != nil {
log.Fatal(err)
}
fmt.Printf("-> plan=%s id is %s\n", arrow, arrowType)
fmt.Printf("->> plan=%s id is %s\n", arrow2, arrow2Type)
fmt.Println("json_extract first tag:", extract)
// Filter and group on JSON paths.
rows, err := db.QueryContext(ctx, `SELECT kind, count(*), group_concat(DISTINCT doc ->> '$.user.id')
FROM events GROUP BY kind ORDER BY kind`)
if err != nil {
log.Fatal(err)
}
for rows.Next() {
var kind, users string
var n int
if err := rows.Scan(&kind, &n, &users); err != nil {
log.Fatal(err)
}
fmt.Printf("kind=%s events=%d users=%s\n", kind, n, users)
}
if err := rows.Err(); err != nil {
log.Fatal(err)
}
rows.Close()
// json_each turns an array into rows.
rows, err = db.QueryContext(ctx, `SELECT t.value, count(*) FROM events, json_each(events.doc, '$.tags') AS t
GROUP BY t.value ORDER BY count(*) DESC, t.value`)
if err != nil {
log.Fatal(err)
}
for rows.Next() {
var tag string
var n int
if err := rows.Scan(&tag, &n); err != nil {
log.Fatal(err)
}
fmt.Printf("tag %s: %d\n", tag, n)
}
if err := rows.Err(); err != nil {
log.Fatal(err)
}
rows.Close()
// The generated column's index serves the lookup.
var plan string
if err := db.QueryRowContext(ctx, "EXPLAIN QUERY PLAN SELECT id FROM events WHERE kind = 'upgrade'").
Scan(new(int), new(int), new(int), &plan); err != nil {
log.Fatal(err)
}
fmt.Println("plan:", plan)
// Decode a whole document in Go when you need the structure.
var raw string
if err := db.QueryRowContext(ctx, "SELECT doc FROM events WHERE kind = 'upgrade'").Scan(&raw); err != nil {
log.Fatal(err)
}
var e Event
if err := json.Unmarshal([]byte(raw), &e); err != nil {
log.Fatal(err)
}
fmt.Printf("decoded: %s by user %d on %s\n", e.Kind, e.User.ID, e.User.Plan)
// json_set edits in SQL; the CHECK still holds.
if _, err := db.ExecContext(ctx, `UPDATE events SET doc = json_set(doc, '$.user.plan', 'team') WHERE id = 2`); err != nil {
log.Fatal(err)
}
if err := db.QueryRowContext(ctx, "SELECT doc FROM events WHERE id = 2").Scan(&raw); err != nil {
log.Fatal(err)
}
fmt.Println("after json_set:", raw)
}The truncated document is rejected by the CHECK. -> returns "free" with quotes and its id is text, while ->> returns free and an integer. Grouping finds two signups by users 7 and 9 and one upgrade by user 7. json_each counts web twice and eu and ios once. The plan line shows SEARCH events USING INDEX events_kind, so the lookup uses the index on the generated column. json_set changes the plan to team in place.
Index a JSON field through a generated column
A query that filters on doc ->> '$.kind' must parse every document unless an index exists. A generated column names the expression once; VIRTUAL computes it on read and costs no storage, STORED computes it on write. An index on the generated column stores the extracted values, and queries that filter on the column use it, as the plan shows. You can also create an index directly on the expression, but then queries must repeat the expression exactly. Generated columns can be added to an existing table with ALTER TABLE ADD COLUMN only when they are VIRTUAL.
ALTER TABLE events ADD COLUMN user_id INTEGER
GENERATED ALWAYS AS (doc ->> '$.user.id') VIRTUAL;
CREATE INDEX events_user ON events (user_id);
SELECT id FROM events WHERE user_id = ?;The new column costs nothing per row because it is VIRTUAL, the index stores each user id once, and the query filters on the column name rather than repeating the path expression.
json_each, json_set and JSONB
json_each is a table-valued function: joined to a table, it returns one row per array element or object member with key, value, type and path columns, which turns tag lists into something you can GROUP BY. json_set, json_insert, json_replace and json_remove return a modified copy of a document, so an UPDATE can change one field without a round trip through Go. Since 3.45 SQLite also supports JSONB, a binary encoding stored as a BLOB and produced by jsonb() and the jsonb_ variants of the functions; it saves reparsing on every read, but it is an SQLite-internal format, so keep TEXT when other programs read the column.
Where Go fits
Marshal documents with encoding/json and bind them as string parameters; scan them back as string or []byte and unmarshal when you need the whole structure. Keep the fields that drive queries, joins and constraints as real columns or generated columns, and the rest in the document. A JSON column is a convenience for optional, evolving data, not a replacement for a schema: NOT NULL, UNIQUE and foreign keys only apply to columns, and json_valid in a CHECK is the minimum validation to add.
TAKE THIS WITH YOU
Store JSON as TEXT with CHECK (json_valid(doc)), read scalars with ->> or json_extract and fragments with ->, expand arrays with json_each, and index the fields you filter on through generated columns.
Check your understanding
A query filters on doc ->> '$.kind' over a million rows and is slow. What lets SQLite use an index for it?
Go to the source
Progress stays in this browser. No account needed.