Skip to content

Instantly share code, notes, and snippets.

@kascote
Last active May 22, 2022 22:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kascote/e7c404a5c27027ff09cf7dd4b635dce4 to your computer and use it in GitHub Desktop.
Save kascote/e7c404a5c27027ff09cf7dd4b635dce4 to your computer and use it in GitHub Desktop.
SQlite JSON queries

JSON and virtual columns in SQLite

reference: https://antonz.org/json-virtual-columns/

select value from events;

{"timestamp":"2022-05-15T09:31:00Z","object":"user","object_id":11,"action":"login","details":{"ip":"192.168.0.1"}}
{"timestamp":"2022-05-15T09:32:00Z","object":"account","object_id":12,"action":"deposit","details":{"amount":"1000","currency":"USD"}}
{"timestamp":"2022-05-15T09:33:00Z","object":"company","object_id":13,"action":"edit","details":{"fields":["address","phone"]}}

this is slow

select
  json_extract(value, '$.object') as object,
  json_extract(value, '$.action') as action
from events
where json_extract(value, '$.object_id') = 11;

but, if define virtual columns:

alter table events
add column object_id integer
as (json_extract(value, '$.object_id'));

alter table events
add column object text
as (json_extract(value, '$.object'));

alter table events
add column action text
as (json_extract(value, '$.action'));

create index events_object_id on events(object_id);

Now the query works instantly:

select object, action
from events
where object_id = 11;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment