1

I have a table in oracle with this definition


    create table PARAM(
       ID VARCHAR(30),
       DOCUMENT   blob
    )

Document is stored in a json format.

{"id":"value","parameters":[{...},{...},{...}]}

How can i extract size for array parameters in sql?

I need extract array size for each table record, and after sum all this values.

ex:

1 step:


    ID    ARRAY_SIZE
    ----  ----------
    1     10
    2     0
    3     3

2 step:


    TOTAL_RECORDS   TOTAL_ARRAYS_SIZE
    -------------   -----------------
    3               13

Can someone please give me an idea how to do that ?

2
  • What version of Oracle are you using? Commented Jul 29, 2020 at 9:37
  • Oracle Database 19c Enterprise Edition Release 19.0 Commented Jul 29, 2020 at 9:47

2 Answers 2

3

Provided you have an is json check constraint on the column, you can use the size() method to get the number elements in an array:

create table t (
  c1 int, 
  c2 varchar2(100) 
    check ( c2 is json ) 
);

insert into t values ( 1, '{ "arr" : [1, 2, 3] }');
insert into t values ( 2, '{ "arr" : [1, 2, 3, 4, 5] }');

select c1, t.c2.arr.size() from t t;

C1    T.C2.ARR.SIZE()   
 1                  3 
 2                  5 
Sign up to request clarification or add additional context in comments.

2 Comments

What version of Oracle does this work on? Oracle 18 db<>fiddle does not work.
18c; you can use it with json_value ( c2, '$.arr.size()' ). Not sure what the issue with dot-notation is
0

For case with a blob field I see the following decision.

You have a table something like this

create table tmp_js
(
   id       number,
   document blob  
);

And table with json objects looks like this

ID    Document 
----  ----------
1     {"id": 1, "paramters": [{"t": 2}, {"t": 3}]}
2     {"id": 2, "paramters": [{"t": 2}, {"t": 3}, {"t": 4}]}
3     {"id": 3, "paramters": [{"t": 2}, {"t": 3}, {"t": 5}, {"t": 6}]}

Then you can resolve your task by following way

Step 1

You will get row's id and size of array in row's document.

select
    t.id,            
    (select
        count(*)
    from
        json_table(json_query(t.document, '$.paramters'), '$[*]' columns (value path '$.t'))
    ) as cnt       
from
    tmp_js t

Step2

You can make total summary from result of first step.

select
    count(*),
    sum(cnt)
from    
    (select
        t.id,            
        (select
            count(*)
        from
            json_table
            (
                json_query(t.document, '$.paramters'), 
                '$[*]' columns (value path '$.t')
            )
        ) as cnt       
    from
        tmp_js t)

Comments

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.