Search code examples
regexstringpostgresqltrimnumeric

Postgresql - How to get numeric value from the end of string and string without end numeric value


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?


Solution

  • 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