0

I have this table and some sample data as well. I want to get the index of each value in array in separate column.

CREATE TABLE contacts (
   id serial PRIMARY KEY,
   name VARCHAR (100),
   phones TEXT []
);

Sample data.

INSERT INTO contacts (name, phones)
VALUES
  (
      'John Doe',
      '{"(408)-589-5846","(408)-589-5555"}'
   ),   
   (
      'Lily Bush',
      '{"(408)-589-5841"}'
   ),
   (
      'William Gate',
      '{"(408)-589-5842","(408)-589-58423"}'
   );

Now I run this query to unnest the data into rows which is something like this.

select name, unnest(phones) from contacts

It gives me the data correctly but I want the number of index for the phone numbers in another column which will help me identify which phone number is at which index. I came to know with array_position() function but it's not working as expected and throwing some error, maybe I'm not putting in right way. I am new to postgresql so any help would be appreciated.

1 Answer 1

2

Use unnest() in the FROM clause and you get the the index using the option with ordinality

select c.name, 
       p.phone,
       p.idx
from contacts c
  cross join lateral unnest(phones) with ordinality as p(phone, idx)
order by c.id, p.idx;

Online example

The above would not return rows from the contacts table that have an empty phones array, if you need that you need to use a LEFT JOIN

select c.name, 
       p.phone,
       p.idx
from contacts c
  left join lateral unnest(phones) with ordinality as p(phone, idx) on true
order by c.id, p.idx;
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.