0

I am trying to extract values between 2 indices in a JSON array using mysql JSON_EXTRACT.

SELECT JSON_EXTRACT('[10, 20, 30, 40,50, 60]', '$[1]');

This query will smoothly return 20 as result. But if I want to get all the numbers between, say, 1st and 3rd indices, how do I query it?

I was expecting something like:

SELECT JSON_EXTRACT('[10, 20, 30, 40,50, 60]', '$[1]..$[3]'); // Not the proper syntax

which will return 20,30,40. But not working.

How do I achieve this?

2
  • Out of curiosity, why are you storing data in a JSON array if you have this type of range query? It's much easier if you store data in normal rows and columns. Commented Sep 15, 2022 at 14:24
  • @BillKarwin This is sort of a temporary table. Not much processing included. Once saved, just return this data for a GET call. The only complicated processing is to get the limit and offset based retrieval. Commented Sep 16, 2022 at 3:04

1 Answer 1

2
SELECT JSON_EXTRACT('[10, 20, 30, 40,50, 60]', CONCAT('$[', idx, ']'))
FROM ( SELECT 1 idx UNION SELECT 2 UNION SELECT 3 ) src;

Of course the indices range can be provided as list/range and converted to rowset in CTE/subquery.

Sign up to request clarification or add additional context in comments.

2 Comments

I have improved the solution by making the following changes: SELECT JSON_EXTRACT('[10, 20, 30, 40,50, 60]', CONCAT('$[', idx, ']')) FROM ( SELECT seq as idx FROM seq_0_to_2) src; Note: I am using mariadb.
@AKA You have not marked your question with mariadb tag... next time always provide precise DBMS version in your question. And I doubt that this really improves the query - it increases its readability, of course, but does not effect the performance and decreases the compatibility.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.