1

How can I cast an array of string into an array of integers?

Below is my array

["6", "5"]

I want convert into int array

[6, 5]
1
  • Do you have a simple postgres array or a JSON array? That looks like a JSON array... Commented Feb 26, 2021 at 15:45

2 Answers 2

1

demo:db<>fiddle

SELECT
    array_agg(elems::int)
FROM unnest(ARRAY['5', '6']) as elems
  1. Expand the array into one record per element
  2. Reaggregate cast integer values

To ensure the original order, you need to add WITH ORDINALITY, which adds an index to the original array:

SELECT
    array_agg(elems.value::int ORDER BY elems.index)
FROM unnest(ARRAY['5', '6']) WITH ORDINALITY as elems(value, index)

If you have a JSON array instead, the algorithm is the same, only the used functions have different names:

SELECT
    json_agg(elems.value::int ORDER BY elems.index)
FROM json_array_elements_text('["5", "6"]'::json) WITH ORDINALITY as elems(value, index)

EDIT: According to comment:

this is my query. SELECT data->>'pid' FROM user_data where data->>'pid' is not null How can I update pid to array of integers ?

demo:db<>fiddle

You have to expand and reaggregate nonetheless:

SELECT 
    json_agg(elems::int)                              -- 2
FROM user_data,
    json_array_elements_text(data -> 'pid') as elems  -- 1
WHERE data->>'pid' IS NOT NULL
GROUP BY id
Sign up to request clarification or add additional context in comments.

4 Comments

this is my query. SELECT data->>'pid' FROM user_data where data->>'pid' is not null How can I update pid to array of integers ?
Please add such information into your questions. Add some sample data and the expected output.
How can I update all pid to array of integer with update statement ?
That's the correct UPDATE. You need to use jsonb_set(): dbfiddle.uk/…
0

You can’t “cast”, but you can get something very close to a cast:

array(select unnest(myArray)::int)

As a testable query:

select array(select unnest(array['5', '6'])::int)

See live demo.

When applying to a column of a selected table:

select
    array(select unnest(myArrayCol)::int)
from myTable

See live demo.

This syntax preserves order.

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.