108

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.

Alexpandiyan Chokkan
  • 1,025
  • 1
  • 10
  • 30
adviner
  • 3,295
  • 10
  • 35
  • 64
  • The `like` operator exists, but a `title` column does not. It is a *property/attribute* of the `data` column, thus [you'll need to extract it's value](https://www.postgresql.org/docs/current/static/functions-json.html) to compare it: `data ->> 'title'` or `data #>> ARRAY['title']` – pozs Mar 21 '17 at 10:05

4 Answers4

149

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%'
Gurwinder Singh
  • 38,557
  • 6
  • 51
  • 76
82

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!

Deep Sehgal
  • 1,052
  • 9
  • 13
  • 1
    This will also search keys, so be careful using this. Only use this if you can guarantee that keys won't have search term. – user961954 May 14 '20 at 01:26
  • If you want to search on the values only and not on the keys, you can try something like select * from table_name where array_to_string( array(select value from jsonb_each_text( )), ' ') like '%Something%' – jlfenaux Jun 05 '20 at 10:16
  • 2
    so much better for quick debugging – Peter F Aug 31 '20 at 13:49
16

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.

nevster
  • 6,271
  • 7
  • 35
  • 42
2

I Think it should be like

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

then only it worked for me.

Karansing
  • 47
  • 6