1

I have the sample data for demostration as shown below:

Table:

create table tbl_jdata
(
id int,
jdata json
);

insert into tbl_jdata values(1,'[{"salary":10000,"name":"mak"},{"salary":20000,"name":"jak"},{"salary":45000,"name":"abc"}]');

I want to display only a json element which is having highest salary for example as shown below in expected result.

Expected Result:

id    jdata
-------------------------------------
1     [{"salary":45000,"name":"abc"}]

My try:

select t.id,each_section
from tbl_jdata t
cross join unnest(t.jdata) each_section
where t.id = 1 and (each_section ->> 'salary') in 
(
 select max(each_section ->> 'salary')
 from tbl_jdata t
 cross join unnest(t.jdata) each_section
);

Getting an error:

ERROR: function unnest(json) does not exist
1
  • @a_horse_with_no_name, Sorry my bad, the actually datatype is json for jdata column and data has been stored in the given format. Commented May 13, 2021 at 15:24

2 Answers 2

2

You need to use json_array_elements() rater than unnest() on a JSON array. You can use a lateral join to get the highest element after doing that:

select t.id, i.*
from the_table t
  cross join lateral (
     select x.item
     from json_array_elements(t.jdata) as x(item)
     order by (x.item ->> 'salary')::int desc
     limit 1
   ) i

Note that the use of jsonb is recommended over json

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

Comments

0

you need to use jsonb, here i am going to send you a references.

https://www.compose.com/articles/faster-operations-with-the-jsonb-data-type-in-postgresql/

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.