Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query last element in array from json structure in postgres

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!

like image 948
Nano Documet Avatar asked Aug 06 '14 21:08

Nano Documet


People also ask

How do I query JSON data in PostgreSQL?

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.

What is -> in PostgreSQL?

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.

Can Jsonb be an array?

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.


2 Answers

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...

like image 138
ig0774 Avatar answered Sep 29 '22 16:09

ig0774


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;
like image 26
Martin Avatar answered Sep 29 '22 15:09

Martin