1

I have a function in oracle that i need converted to postgres.

i can't seem to find a reason for this difference in docs docs but:

oracle:

SELECT substr('1236',-4, 4) FROM DUAL;
    Result: 1236

postgres:

SELECT substr('1236',-4, 4);
    Result: empty (Null)

i need an output similiar to oracle and i cant seem to understand why the postgres function differs, and what i can use as an alternative

3
  • 5
    substr() doesn't accept a negative starting position in Postgres Commented Feb 24, 2021 at 12:19
  • hmmm, any idea for the nearest alternative? Commented Feb 24, 2021 at 12:21
  • It does accept, but shows different beheavior, select substr('string', -1, 3) returns st. I think it assumes you have something in -ve positions, and takes in account but returns only the valid values, so above returns select substr('string', 1, 1) Commented Feb 6, 2023 at 17:11

1 Answer 1

4

I'm a little confused by your confusion. Oracle is quite clear that a negative position counts back from the end of the string.

Nothing in the Postgres documentation suggests that this behavior. There is no mention of negative positions (as far as I can tell) for any string functions other than left() and right(). And no hint whatsoever that negative positions have a special meaning in other contexts.

Postgres fortunately has a simpler way to do what you want:

select right('1236', 4)
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.