I have a column that is using the JSON type. I would like to perform a query to select all distinct records for a particular field in the JSON string: I.e. given these three documents
{
id: 1,
s: "foo"
},
{
id:2,
s: "bar"
},
{
id:3,
s: "foo"
},
the query must check the "s" key for distinct values and return the documents with id 1 and 2.
Best Answer
Assuming a JSON array in a Postgres 9.4
jsonb
column, this would do the job:Or, unless
s
is a nested object, it's probably cheaper to fold on thetext
value instead of thejsonb
(sub-)record. Just use the operator->>
instead of->
in this case. The result is the same:Replace the subquery
t
with your actual table.Key elements are
jsonb_array_elements()
(orjson_array_elements()
) in aLATERAL
join withWITH ORDINALITY
and then the Postgres-specificDISTINCT ON
.Related, with more explanation: