2

In postgresql db I have a 'data' column which type is json. It looks like following:

{"columns":[{"name":"cusno","displayName":"Customer number","type":"text"},{"name":"cname","displayName":"Name","type":"text"},{"name":"cadd1","displayName":"Address","type":"text"},{"name":"cstte","displayName":"State","type":"text"}],"variables":[{"name":"var1", "type":"text"}, {"name": "var2","type":"text"}]}

I need to do search for example when user types 'cu' it should return rows which columns name or display name contains this word or variables name contains this word. How should i write the where clause ?

asked Jun 19, 2017 at 12:13

1 Answer 1

3

Test table & data:

create table jsontest
(
jsoncolumn json
);
insert into jsontest values ('{"columns":
[{"name":"cusno","displayName":"Customer number","type":"text"},
{"name":"cname","displayName":"Name","type":"text"},
{"name":"cadd1","displayName":"Address","type":"text"},
{"name":"cstte","displayName":"State","type":"text"}],
"variables":[{"name":"var1", "type":"text"}, 
{"name": "var2","type":"text"}]}');

Query:

with data as 
( select json_array_elements( jsoncolumn ->'columns' ) as element 
 from jsontest
)
select * 
from data 
where cast(element->>'name' as varchar) like '%cu%' 
or cast(element->>'displayName' as varchar) like '%cu%';

Test:

postgres=# with data as ( select json_array_elements( jsoncolumn ->'columns' ) as element from jsontest )
select * from data where cast(element->>'name' as varchar) like '%cu%' or cast(element->>'displayName' as varchar) like '%cu%';
 element
----------------------------------------------------------------
 {"name":"cusno","displayName":"Customer number","type":"text"}
(1 row)
postgres=#
answered Jun 19, 2017 at 12:34
1
  • 4
    You don't have to cast ->> returns text. You also can clean that up by using CROSS JOIN LATERAL rather than the CTE. SELECT foo.* FROM foo CROSS JOIN LATERAL jsonb_array_elements(json->'columns') AS col WHERE col->>'name' LIKE '%cu%' OR col->>'displayName' LIKE '%cu%'; Commented Jun 19, 2017 at 18:54

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.