0

I have a field that holds JSONB arrays. How can I delete the last item?

[
  {
    "name": "test1",
  },
  {
    "name": "test2",
  },
]

1 Answer 1

2

You can use jsonb_column - (-1). See the documentation.


WITH data(j) AS (
    VALUES ('[
      {
        "name": "test1"
      },
      {
        "name": "test2"
      },
      {
        "name": "test3"
      }
    ]'::JSONB)
)
SELECT j, j - (-1) AS all_but_last, j - 1 AS without_second_element
FROM data;
j all_but_last without_second_element
[{"name":"test1"},{"name":"test2"},{"name":"test3"}] [{"name":"test1"},{"name":"test2"}] [{"name":"test1"},{"name":"test3"}]

View on DB Fiddle

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

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.