Search code examples
sqlpostgresqljoinjsonb

Postgres: How to join table with values from jsonb[] column


I have two tables as follows

accounts
 ------------------------------------------
|  ID  |           LOCATIONS               |
|------------------------------------------|
|  1   |  [{ "id" : 1}, { "id" : 3 }]      |
|------------------------------------------|
|  2   |             []                    |
 ------------------------------------------

regions
 ----------------------------
|  ID  | DATA               |
|---------------------------|
|  1   | {"name": "South"}  |
|---------------------------|
|  2   | {"name": "West"}   |
|---------------------------|
|  3   | {"name": "North"}  |
|---------------------------|
|  4   | {"name": "East"}   |
---------------------------

locations is of type jsonb[]

Now I wanted to get result as follows

 ------
| NAME |
|------|
| South|
|------|
| North|
 ------

Please help with the postgresql query to get this.


Solution

  • Edited for jsonb[] type:

    Demo

    select
      r.data ->> 'name' as name
    from
      accounts a
      cross join unnest(a.locations) al
      inner join regions r on r.id = (al ->> 'id')::int
    

    P.S: for jsonb type:

    You can use jsonb_to_recordset function and CROSS JOIN to join JSON array record with table.

    Demo

    select
      r.data ->> 'name' as name
    from
      accounts a
      cross join jsonb_to_recordset(a.locations) as al(id int)
      inner join regions r on r.id = al.id