1

I have a table like this:

TestTable
---------
data (TEXT)

All data values are JSON objects like { a:1, b:2, c:3 }.

I want to be able to query the database and ORDER BY data->b DESC without a full table scan (indexed).

Is this possible in SQLite JSON1?

forpas
  • 160,666
  • 10
  • 38
  • 76
Lucien
  • 776
  • 3
  • 12
  • 40

1 Answers1

1

Use the function json_extract():

SELECT * 
FROM TestTable
ORDER BY json_extract(data, '$.b') DESC;

See the demo.

If the values for b are quoted then cast to numeric:

SELECT * 
FROM TestTable
ORDER BY json_extract(data, '$.b') + 0 DESC;

See the demo.

forpas
  • 160,666
  • 10
  • 38
  • 76
  • If I make an index on `$.b`, will this operation use the index or do a full table scan? – Lucien Dec 25 '21 at 22:36
  • 1
    @Lolums Check this: https://dbfiddle.uk/?rdbms=sqlite_3.27&fiddle=c8f528e28b9d86df9dcd85becb3f86e4 The index is used. – forpas Dec 25 '21 at 22:42