0

I would like to access first 5 elements of an array "ingredients" before UNNESTing the array:

SELECT 
    TRIM
    (REGEXP_REPLACE
        (UNNEST
            (string_to_array(ingredients, ';'))[1:5], '\S+\%|\s+\(.*?\)','','g'))
FROM products 

The "Ingredients" array may contain values such as:

{'1%', 'abc(2%)', 'abcd', ... , N th element}

The code below works fine but I don't know what's wrong with the above code.

SELECT (string_to_array('1,2,3,4',','))[1:3]

1 Answer 1

1

This works:

select
  trim(
    regexp_replace(
      unnest(
        (string_to_array(ingredients, ';'))[1:5]
      ),
      '\S+\%|\s+\(.*?\)',
      '',
      'g'
    )
  )
from products;

Your example shows how important is to maintain good formatting/indentation.

The following is the same as what you wrote, but re-formatted (opening parenthesis is next to function itself, closing one is at the same indentation level, anything inside is indented more):

SELECT 
    TRIM(
        REGEXP_REPLACE(
           UNNEST(
               string_to_array(ingredients, ';')
           )[1:5],
           '\S+\%|\s+\(.*?\)',
           '',
           'g'
        )
    )
FROM products 

-- the mistake is obvious, you're trying to apply [1:5] to an already unnested result set, not to an array.

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.