1

I'm trying to search for the array position of a matching string, I see there is a post with the position of a character on a string but not one with an array, here is an example of what I want to achieve:

array['potato-salad','cucumber-salad','eggplant-pie','potato-soup']

I want to know where the elements containing the word 'potato' are, so the result should be something like this:

[1,4] 

I was trying to obtain the lengths of all elements, then converting the array to string, and searching for the string to see where the string matches and compare if the position can go in between any of the array elements lengths, but this doesn't work if my number of elements in the array is variable, and in my problem it is.

1 Answer 1

3

If you want exact match use array_positions:

CREATE TABLE my_tab(ID INT, col VARCHAR(100)[]);

INSERT INTO my_tab(ID, col)
VALUES (1, array['potato-salad','cucumber-salad','eggplant-pie','potato-soup']),
       (2, array['potato']);

Query:

SELECT *
FROM my_tab
,LATERAL array_positions(col, 'potato-salad') AS s(potato_salad_position)
WHERE s.potato_salad_position <> '{}';

Output:

╔════╦════════════════════════════════════════════════════════╦═══════════════════════╗
║ id ║                          col                           ║ potato_salad_position ║
╠════╬════════════════════════════════════════════════════════╬═══════════════════════╣
║  1 ║ {potato-salad,cucumber-salad,eggplant-pie,potato-soup} ║ {1}                   ║
╚════╩════════════════════════════════════════════════════════╩═══════════════════════╝

If you want to use LIKE search with wildcards you could use unnest WITH ORDINALITY:

SELECT id, array_agg(rn) AS result
FROM my_tab
,LATERAL unnest(col) WITH ORDINALITY AS t(val,rn)
WHERE val LIKE '%potato%'
GROUP BY id;

Output:

╔════╦════════╗
║ id ║ result ║
╠════╬════════╣
║  1 ║ {1,4}  ║
║  2 ║ {1}    ║
╚════╩════════╝
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.