0

I have to do a select based on a regular expression and return some values of the expression as columns.

I managed to do something similar to this

select
(regexp_matches(value, '...', 'g'))[1] as expressionValue1,
(regexp_matches(value, '...', 'g'))[2] as expressionValue2,
(regexp_matches(value, '...', 'g'))[5] as expressionValue3
from table

I am trying to rewrite the query to something like this

select 
    (resultsq)[1] as expressionValue1,
    (resultsq)[2] as expressionValue2,
    (resultsq)[3] as expressionValue3
from (
    select
    regexp_matches(value, '...', 'g') 
    from table
) resultsq

However, I get a syntax error. I think the result text[] is being transformed to text.

I want to do it this way because I understand that the regular expression is evaluated only one time per tuple and the code is clearer.

The regular expression that I have to apply is relatively long and complex and there are many fields to extract.

1 Answer 1

1
    (resultsq)[1] as expressionValue1,
    (resultsq)[2] as expressionValue2,
    (resultsq)[3] as expressionValue3 ```

You are referencing the subquery alias resultsq rather than the field name, hence array indexing on it doesn't work. The subquery is returning a set of rows with a field named regexp_matches, so reference that in your statement and it will work.

select 
    (regexp_matches)[1] as expressionValue1,
    (regexp_matches)[2] as expressionValue2,
    (regexp_matches)[3] as expressionValue3

https://www.db-fiddle.com/f/g6zdgdo7Jv6x2boL4NKi9m/0

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.