0

I have the following query:

select position( '/s/' in col)
from table

This works.

Now, I want to be able to find the position of /s/ or /d/ or /c/

I tried:

select position( '[/s/][/c/][/d/]' in col)
from table

But it returns a wrong value.

Example:

select position( '/s/' in '/s/')

returns 1.

select position( '[/s/][/d/][/c/]' in '/s/')

returns 0

How can I solve this?

Edit:

  • It can contains only one of /s/ or /d/ or /c/. The string will not contain /s/d/ etc...

  • There can't be more the one occurrences of the matched sub-string. The string won't contain '/s/..../s/'

In simple words - I'm looking for the first occurrence of /s/ or /d/ or /c/ don't worry about the edge cases.

7
  • @a_horse_with_no_name prestodb running over amazon. Commented Aug 19, 2018 at 15:12
  • What if col contains both /s/ and /d/? Does it matter which position to return if there are multiple matches? Commented Aug 19, 2018 at 15:16
  • @RuudHelderman it won't. It can contains only one of them. It's indenture that it contains only one occurrence of such. Commented Aug 19, 2018 at 15:16
  • Are you sure you can use patterns there? If yes, try position('/s/|/d/|/c/' in '/s/'). Commented Aug 19, 2018 at 15:34
  • @stickybit doesn't work. I need a way to make it work other than write different position query for each sub-sring :( Commented Aug 19, 2018 at 15:37

2 Answers 2

2

This might do the trick:

SELECT MAX(patlist.pattern) FROM (VALUES (POSITION('/s/' IN col)), (POSITION('/d/' IN col)), (POSITION('/c/' IN col))) AS patlist(pattern)

Wrapped inside a query:

SELECT (SELECT MAX(patlist.pattern) FROM (VALUES (POSITION('/s/' IN col)), (POSITION('/d/' IN col)), (POSITION('/c/' IN col))) AS patlist(pattern))
FROM MyTable

Disclaimer: in absence of a prestodb instance, I could only test it on an alternate database engine. It may or may not work on prestodb.

Sign up to request clarification or add additional context in comments.

Comments

1

Since you wrote in the comments, that only one of the substrings will be present and position() returning 0, if the substring isn't found, you just can check the sum of multiple position()s.

SELECT position('/s/' in col)
       +
       position('/d/' in col)
       +
       position('/c/' in col)
       FROM table;

Or even nicer, since Presto has a greatest() function, you could do:

SELECT greatest(position('/s/' in col),
                position('/d/' in col),
                position('/c/' in col))
       FROM table;

Like that you get the greatest position.

1 Comment

Yeah I thought of this solution but wanted to know if there is a way to avoid the multiple position queries.. I have like 15 of theses :(

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.