Postgresql json like query

PostgresqlJsonb

Postgresql Problem Overview


I have the following table called module_data. Currently it has three rows of entries:

				id                               data
0ab5203b-9157-4934-8aba-1512afb0abd0 {"title":"Board of Supervisors Meeting","id":"1i3Ytw1mw98"}
7ee33a18-63da-4432-8967-bde5a44347a0 {"title":"Board of Supervisors Meeting","id":"4-dNAg2mn6o"}
8d71ca35-74eb-4751-b635-114bf04843f1 {"title":"COPD 101", "id":"l9O0jCR-sxg"}

Column data's datatype is jsonb. I'm trying to query it using like operator. Something like the following:

SELECT * FROM module_data WHERE title LIKE '%Board%';

I've been looking at the jsonb support and there doesn't seem to be a like operator. If anyone has any advice.

Postgresql Solutions


Solution 1 - Postgresql

If the data column is text type, then use ->> on cast:

select * from module_data where data::json->>'title' like '%Board%'

If it's already json:

select * from module_data where data->>'title' like '%Board%'

Solution 2 - Postgresql

I found the following is more straight-forward and easier for jsonb type of columns:

select * from table_name
where 
column_name::text like '%Something%'

Found a good article on more examples and implementations: https://www.compose.com/articles/faster-operations-with-the-jsonb-data-type-in-postgresql/

Hope it helps!

Solution 3 - Postgresql

One other option which may be sufficient for other people who've found this page is to just cast the column to text type. Eg

select * from module_data where data::text like '%Board%'

Note though, this will search over the entire json and should only be used if you can guarantee the other fields won't be a problem.

Solution 4 - Postgresql

I Think it should be like

select * from module_data where data->>'$."title"' like '%Board%'

then only it worked for me.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionadvinerView Question on Stackoverflow
Solution 1 - PostgresqlGurwinder SinghView Answer on Stackoverflow
Solution 2 - PostgresqlDeep SehgalView Answer on Stackoverflow
Solution 3 - PostgresqlnevsterView Answer on Stackoverflow
Solution 4 - PostgresqlKaransingView Answer on Stackoverflow