0

How do we substring from reverse in Postgres? In oracle we can provide the no.of occurrences of the pattern and extract the expected records. In Postgres we do not have such option. I tried using substring(), left() and right() functions, still it is not working. Any suggestion would be helpful.

Value in the column,

col1
100~500~~~~Bangalore~~~~KA~null~Train

Expected result,

Train
1
  • Do you want the string after the last ~? Or the string between the (n)th and the (n+1)th occurrence of ~? Commented Jul 13, 2021 at 9:24

1 Answer 1

3

To get the characters after the last ~ you can use substring() with a regex:

substring(col1 from '~([^~]+)$')

Or get the position of the last ~ by using the reverse function:

right(col1, strpos(reverse(col1), '~') - 1)

A more general approach is to convert the string to an array, then pick the last array element:

(string_to_array(col1, '~'))[cardinality(string_to_array(col1, '~'))]

The best solution to this sort of problems is to not store multiple values delimited by some character in a single column. If you really need to de-normalize using arrays or JSON would at least be a bit more flexible (and robust)

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.