1

I have the following usernames in Postgresql user table.

**username**
test
123test
123test456
test123
test45test
test55test55

So I am trying to get the string without end numeric value and end numeric value seperately.

I am expecting following output

str          num
----------------
test         0
123test      0
123test      456
test         123
test45test   0
test55test   55

How to write a Postgresql query that will return the above result?

1 Answer 1

1

You could use regexp_replace() and substring():

select
    regexp_replace(username, '\d+$', '') str,
    coalesce(substring(username from '\d+$')::int, 0) num
from mytable

Demo on DB Fiddlde:

with mytable as (
    select 'test' username
    union all select '123test'
    union all select '123test456'
    union all select 'test123'
    union all select 'test45test'
    union all select 'test55test55'
)
select
    regexp_replace(username, '\d+$', '') str,
    coalesce(substring(username from '\d+$')::int, 0) num
from mytable
str        | num
:--------- | --:
test       |   0
123test    |   0
123test    | 456
test       | 123
test45test |   0
test55test |  55
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.