Johnny Metz
Johnny Metz

Reputation: 5965

sql: get distinct values from jsonb column

I'm trying to get the distinct sample_id values from a PostgreSQL database table. This would be simple besides the fact that they're embedded in a JSONB field.

Here's what my database looks like when I run select * from event limit 10:

 id | step | event_date | event_status |           payload
----+------+------------+--------------+-----------------------------
  1 |    1 | 2018-01-10 | success      | {"x": "y", "sample_id": [0]}
  2 |    2 | 2018-01-12 | success      | {"x": "y", "sample_id": [0]}
  3 |    3 | 2018-01-14 | success      | {"x": "y", "sample_id": [0]}
  4 |    1 | 2018-01-13 | success      | {"x": "y", "sample_id": [1, 38, 63]}
  5 |    2 | 2018-01-15 | success      | {"x": "y", "sample_id": [1]}
  6 |    3 | 2018-01-17 | pending      | {"x": "y", "sample_id": [1]}
  7 |    1 | 2018-01-16 | success      | {"x": "y", "sample_id": [2]}
  8 |    2 | 2018-01-18 | success      | {"x": "y", "sample_id": [2, 55]}
  9 |    3 | 2018-08-20 | success      | {"x": "y", "sample_id": [2]}
 10 |    1 | 2018-01-19 | success      | {"x": "y", "sample_id": [3]}

For the following output I should be getting following data back: [0, 1, 2, 3, 38, 55, 63] (sorted order doesn't really matter).

I've looked into using the JSONB field functions but having no luck. Any idea how to construct such a query?

Upvotes: 0

Views: 2695

Answers (1)

Oto Shavadze
Oto Shavadze

Reputation: 42773

Try with jsonb_array_elements_text

select distinct jsonb_array_elements_text(payload->'sample_id') 
from event

or, if you want values as an array and not records set, then you can:

select array_agg(distinct e.v) from event 
join lateral jsonb_array_elements_text(payload->'sample_id') e(v)
on true

Upvotes: 3

Related Questions