Storing and querying supplier events with SQLite 3.45 JSONB
SQLite JSONB arrived in January 2024. An example supplier event table separates binary document storage, input validation, and an index that supports the queries operators actually run.
Archive retrospective · Topic year 2024
In this article
Start with the queries that read the documents
A warehouse receives shipment events from three suppliers. Each sender includes an event type, an order reference, and a selection of transport attributes. Operators open a screen showing the twenty newest shipments. Support staff occasionally open an individual record to inspect its source details. Both features use the same table, but they put different pressure on storage. The list should find the matching rows early. The detail screen needs fields from one document. SQLite 3.45.0 shipped on January 15, 2024. Its JSON functions can store the internal parse tree as JSONB. A later operation can use that binary representation without parsing the same text again. Before changing an existing application, count which queries read the same document frequently and inspect where that work happens. A nightly export and an interactive search screen are likely to have different priorities.
Keep storage and lookup decisions separate
SQLite manages JSONB as a BLOB. PostgreSQL uses a different binary representation under the same name. For a portable export, ask SQLite for text JSON. The receiving application can then read the file with its own tooling. The SQLite documentation describes most JSONB operations as O(N), the same complexity class as text JSON for those operations. The binary representation can save parsing work. An index helps the engine reach selected rows in the first place. Consider a shipment containing twenty product lines. An operator can reasonably open the full list from one row. Searching millions of shipments for the same product code changes the design problem. If that becomes a central workflow, model an indexed attribute or a relation for product lines and measure the workload again. Document which values belong to the supplier contract and which values belong to the database layout.
Build around the operator’s list
In the example, tenant_id identifies the warehouse or account. The application records received_at as Unix seconds. SQLite derives event_type from the payload through a virtual generated column. The compound index supports the tenant and type equality conditions and the requested descending timestamp order. The query reads the units field for the rows it returns. The insert converts text to a BLOB through jsonb. The storage-class check and strict JSONB validation protect the stored representation. The second check uses IS so a missing type makes the comparison false. A CHECK expression that evaluates to SQL NULL can otherwise accept a row. Keep domain validation at the ingress boundary as well. For example, confirm that the sender is permitted to use the tenant, that a unit count is within range, and that an event type belongs to the contract.
CREATE TABLE supplier_event (
id INTEGER PRIMARY KEY,
tenant_id INTEGER NOT NULL,
received_at INTEGER NOT NULL,
payload BLOB NOT NULL CHECK (typeof(payload) = 'blob' AND json_valid(payload, 8)),
event_type TEXT GENERATED ALWAYS AS (json_extract(payload, '$.type')) VIRTUAL,
CHECK (json_type(payload, '$.type') IS 'text')
) STRICT;
CREATE INDEX supplier_event_lookup
ON supplier_event (tenant_id, event_type, received_at DESC);
INSERT INTO supplier_event (tenant_id, received_at, payload)
VALUES (7, 1710500400, jsonb('{"type":"shipment","units":12}'));
EXPLAIN QUERY PLAN
SELECT id, received_at, json_extract(payload, '$.units') AS units
FROM supplier_event
WHERE tenant_id = 7 AND event_type = 'shipment'
ORDER BY received_at DESC
LIMIT 20;
Practice validation and export before migration
Check the SQLite version on the connection that actually opens the database. A bundled mobile or desktop driver can differ from the command line executable. Copy a small batch into a staging table and compare field types and values before scheduling a wider migration. Test an absent key, an explicit JSON null, a large document, a duplicate inbound event, and an event type represented as a number. Give each case an expected outcome. The value 8 asks json_valid for strict validation of the binary format. When an integration requires standard text JSON as its input, validate the text with the relevant mode before converting it. A query that calls json(payload) makes the resulting export usable with a text JSON parser. Test the restored data with the oldest supported client, especially when the application ships its own SQLite library.
SELECT sqlite_version() AS engine_version;
SELECT id, json_valid(payload, 8) AS valid_jsonb,
json_extract(payload, '$.type') AS event_type,
json_type(payload, '$.units') AS units_type,
json_extract(payload, '$.units') AS units,
json(payload) AS portable_json
FROM supplier_event
WHERE tenant_id = 7;
Measure read and write workloads separately
Set up a text table and a JSONB table using the same logical index. Feed both tables the same rows. Test a single detail read, an indexed list with a short result set, and a complete export. Capture repeated runs and report a median and a slower percentile. Record whether each test starts with a warmed cache. That helps a second developer reproduce the conditions. Repeat the write test using the same transaction sizes and durability settings. Record elapsed time and file size for each table. EXPLAIN QUERY PLAN helps confirm which predicates an index supports and whether the engine sorts separately. The textual details of that output can change across SQLite versions. Store them as diagnostic evidence and compare the behavior of interest in an automated regression check.
Make the deployment decision from evidence
Give the change three acceptance criteria. The read queries should reflect actual operator workflows, the write path should meet throughput targets, and an export and restore should work with the supported clients. Try incremental rollout on new records if the measured benefit justifies the added format. When replacing an existing table, rehearse a rollback with representative data and keep an explicit window for any reader version that still uses the old representation. A supplier may later add fields or change how an attribute is used. Revisit the index when a field becomes a frequent filter. Review its type and unit, then measure the list and export paths again. Separating how a document is stored from how the application finds an event gives the team two independent decisions to revisit as the workload grows.
Reader discussion
Which bottleneck would you expect as this solution scales?
No comments yet. Be the first to contribute.
Write a comment