Let's say that we have the following
{ "items" :
[
{"id": 1},
{"id": 2},
{"id": 3}
]
}
How can I get the last element from the array in the given json structure? Getting the first one seems not that complicated
SELECT t.column->'items'->0 AS elem
FROM tbl t
WHERE other_column = 20;
Thanks in advance!
Querying the JSON documentPostgreSQL has two native operators -> and ->> to query JSON documents. The first operator -> returns a JSON object, while the operator ->> returns text. These operators work on both JSON as well as JSONB columns. There are additional operators available for JSONB columns.
PostgreSQL provides two native operators -> and ->> to help you query JSON data. The operator -> returns JSON object field as JSON. The operator ->> returns JSON object field as text.
jsonb[] is not an "extra" datatype, it's simply an array of JSONB values. Similar to text[] or integer[] . You can create arrays from every type.
Something like this should get the last element of your example:
SELECT t.col->'items'->(json_array_length(t.col->'items')-1)
FROM tbl t
SQLFiddle showing this in action...
In Postgres 9.5+ one can now use negative subscripts to achieve this.
For your case above, getting the last element could be achieved by:
SELECT t.column->'items'->-1 AS elem
FROM tbl t
WHERE other_column = 20;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With