1

How do I dynamically SELECT the last array value in a JSON type column in PostgreSQL?

id: 2927
material_size: [".016 x 1.156","0","1"]

I could statically retrieve the last value "1" using:

 SELECT material_size->>2 AS material_size FROM table_name;

However that would always get the second record instead of the last record (if the number of values isn't exactly three).

1
  • 1
    To be precise: ` material_size->>2 ` would get the third element, not the ` second record `. Commented Mar 20, 2015 at 18:21

2 Answers 2

1

You can get the length of the JSON array and use that (minus one) as the index:

with t1 as (select 2927 id, '[".016 x 1.156","0","1"]'::json material_size)
select material_size->>(json_array_length(material_size)-1) from t1;

See http://www.postgresql.org/docs/9.4/static/functions-json.html.

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

3 Comments

... why are you presuming I have data from the database before I've made the query?
I'm not sure what you mean... are you referring to the CTE? That was just for demonstration purposes (to make this a self-contained example). And the solution itself is just reusing the material_size column, so it's not pulling/using data that isn't received from the query...
Okay; I'll have to come back to this soon to verify and accept, thanks!
1

You can use negative index to query elements in a JSON value from the end:

 SELECT material_size->>-1 AS material_size FROM table_name;

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.