Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining order of elements inside json_array - SQL

Tags:

I have a table kind of like this, let's call it base_table:

id |    date     |     json_array
---+-------------+------------------
1    2018-01-01    [{..a..},{..b..}]
2    2018-01-01    [{..c..}]
3    2018-01-01    [{..d..}]
4    2018-01-01    [{..e..},{..f..}]
.        .                 .
.        .                 .
.        .                 .

The json_array column always has either 1 or 2 elements.

I need to make a select in SQL where on each line I can show: the respective id from base_table; its order (if the element comes 1st or 2nd inside the array); the element of the json_array.

The output should be something like this:

id | order | json_object
---+-------+------------
1     1        {..a..}
1     2        {..b..}
2     1        {..c..}
3     1        {..d..}
4     1        {..e..}
4     2        {..f..}
.     .           .
.     .           .
.     .           .

But I'm having a lot of trouble with showing the order of the elements... Can anyone help?

The database is in PostgreSQL 9.6.1

like image 754
David Silva Avatar asked May 10 '18 19:05

David Silva


1 Answers

Use json_array_elements(json_array) with ordinality:

with my_table(id, json_array) as (
values
    (1, '[{"a": 1}, {"b": 2}]'::json),
    (2, '[{"c": 3}]'),
    (3, '[{"d": 4}]'),
    (4, '[{"e": 5}, {"f": 6}]')
)

select id, ordinality, value
from my_table
cross join json_array_elements(json_array) with ordinality;

 id | ordinality |  value   
----+------------+----------
  1 |          1 | {"a": 1}
  1 |          2 | {"b": 2}
  2 |          1 | {"c": 3}
  3 |          1 | {"d": 4}
  4 |          1 | {"e": 5}
  4 |          2 | {"f": 6}
(6 rows)    

DbFiddle.

Read 7.2.1.4. Table Functions in the documentation.

like image 173
klin Avatar answered Oct 04 '22 19:10

klin