18

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!

3
  • Do you always have a simple uniform JSON structure? Because a simple, inelegant trick would be to find a substring. Commented Aug 6, 2014 at 21:49
  • The json structure will need more information than the one I provided. It was more illustrative than anything else, hoping to have an easy answer. I am interested on how you could handle it using substring. Thanks! Commented Aug 6, 2014 at 22:01
  • You can use Regex's in your SQL on strings, and treat your JSON as a string: postgresql.org/docs/9.1/static/functions-matching.html - if you know that the JSON ends with }]}, you can find the element that precedes that - it's messy, and PostgreSQL has better ways of handling it. Commented Aug 6, 2014 at 22:10

2 Answers 2

22

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

Sign up to request clarification or add additional context in comments.

1 Comment

For me, the function name had to be caps for it to work (windows, perhaps?) JSONB_ARRAY_LENGTH/JSON_ARRAY_LENGTH
4

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.